Excel 2007,VBA导入新的.csv文件以更新现有选项卡

时间:2011-07-19 14:21:14

标签: excel-vba excel-2007 updating import-from-csv vba

我刚刚熟悉VBA语言,并感谢任何帮助。我正在尝试编写一个用新文件更新现有选项卡的程序。 这是我到目前为止所做的:

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

但问题出在第三部分的前两行,它指向一个特定的文件。但我希望程序导入我专门选择的任何文件。我想我要问的是如何链接第二部分提示窗口打开文件,第三部分链接该目录地址代替当前SPECIFIC目录地址。

1 个答案:

答案 0 :(得分:0)

使用连接运算符&并将传递给连接的字符串设为"TEXT;" & aFile

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

另外,我想在第7行代替"False"而不是False