Excel macro - Import cvs files into an Excel file

Post Reply
wwj
Posts: 2497
Joined: 27 Jan 2007 08:16

Excel macro - Import cvs files into an Excel file

Post by wwj »

Code: Select all


Sub importBCFile(folder As String, inputSheet As String)
    
'   inputSheet: Data file name without .csv extension.
    
'   Basin Parameters.
    filePath = ActiveWorkbook.Path & "\" & folder & "\"
    inputFile = inputSheet & ".csv"
    
'   [1] If needed, change an old result sheet. - Current workbook.
    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = inputSheet Then
            exists = True
        End If
    Next i
    
    If exists Then
        Worksheets(inputSheet).Select
        'Worksheets(inputSheet).Name = inputSheet & "_Old"       ' Backup.
        Application.DisplayAlerts = False
        Worksheets(inputSheet).Delete
        'Worksheets("TrTgt_Old").Delete
        Application.DisplayAlerts = True
    End If
    
'   [2] Import an output file: *.csv
    stdWorkbook = ActiveWorkbook.Name
    Workbooks.Open Filename:=filePath & inputFile
 
    Sheets(inputSheet).Select
    Sheets(inputSheet).Move Before:=Workbooks(stdWorkbook).Sheets(1)
    
End Sub

wwj
Posts: 2497
Joined: 27 Jan 2007 08:16

Re: Excel macro - Import cvs files into an Excel file

Post by wwj »

The following code is much better!

https://stackoverflow.com/questions/121 ... xcel-sheet

Code: Select all


    For segN = 1 To numSeg ' segments
    
        outSht = oSht & segN
        
        ' Clear the existing contents
        Sheets(outSht).Activate
        ActiveSheet.UsedRange.Select
        Selection.ClearContents
        
        Set ws = ActiveWorkbook.Sheets(outSht) 'set to current worksheet name
        
        For i = 1 To numTS  ' time steps
        
            inputSheet = iSht & "-S-" & segN & "-t-" & i
            inputFile = filePath & "\" & inputSheet & ".csv"
            
            j = (i - 1) * 3 + 1
            ws.Cells(1, j) = i
            
            '   Import an output file (*.csv) and Copy the values.
            With ws.QueryTables.Add(Connection:="TEXT;" & inputFile, Destination:=ws.Range(ws.Cells(1, j + 1), ws.Cells(1, j + 1)))
                 .TextFileParseType = xlDelimited
                 .TextFileCommaDelimiter = True
                 .Refresh
            End With

        Next i
    Next segN
    
Post Reply