Search code examples
excelexcel-2007updatingimport-from-csvvba

Excel 2007, VBA import new .csv files to update existing tab


I've just been acquainting myself with the VBA language and would appreciate any help. I'm trying to write a program that updates an existing tab with a new file. Here's what I have so far:

Sub ImportFile()
'
' ImportFile Macro
'
' Keyboard Shortcut: Ctrl+Shift+I

    ' Clears active sheet
    Cells.Select
    Selection.ClearContents
    Range("A1").Select

    ' "Open" prompt window
    Dim aFile As String
    aFile = Application.GetOpenFilename(FileFilter:="Comma separated values files, *.csv")
    If aFile = "False" Then Exit Sub



    ' Import .csv file to active sheet
     With ActiveSheet.QueryTables.Add(Connection:= _
       "TEXT;C:\Users\jiarui.hou.THRUBIT\Desktop\thrubit\data\PS25R_175c_20110711_proc1.csv" _
        , Destination:=Range("$A$1"))
        .Name = "PS25R_175c_20110711_proc1"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

But the problem is in the first two lines of the third part, it directs to a specific file. But I want the program to import ANY file that I had specifically selected. I guess what I'm asking is how do I link the second part which prompts a window to open a file, to the third part which links that directory address in place of the current SPECIFIC directory address.


Solution

  • Use the concatenation operator & and make the string that you pass to connection be "TEXT;" & aFile

     With ActiveSheet.QueryTables.Add(Connection:= "TEXT;" & aFile, Destination:=Range("$A$1"))
    

    Also, I think instead of "False" you want False on the 7th line.