Excel宏:导入特定的CSV文件而不是选择它

时间:2017-10-06 06:27:16

标签: excel vba excel-vba csv

我使用以下宏将CSV文件导入Excel。 宏本身工作正常,但是当我启动宏时,我总是要选择要导入的CSV文件(出现文件选择对话框)。

有没有办法自动选择C:\test\testfile.csv而不是文件选择对话框?

谢谢!

Sub GetCSVList()
    Dim dlgOpen As FileDialog
    Set dlgOpen = Application.FileDialog(msoFileDialogFilePicker)

    Application.DisplayAlerts = False
    On Error Resume Next
    Worksheets("Tickets").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    With dlgOpen
        .AllowMultiSelect = False
        ''Start in
        .InitialFileName = "C:\test"
        .Show
    End With

    For Each fname In dlgOpen.SelectedItems
        ImportCSV fname
    Next
End Sub


Sub ImportCSV(fname)
    Set ws = Worksheets.Add(after:=Worksheets(Worksheets.Count))
    ws.Name = "Tickets"

    With ws.QueryTables.Add( _
            Connection:="TEXT;" & fname, _
            Destination:=Range("A1"))
        .Name = "Test" & Worksheets.Count + 1
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .Refresh BackgroundQuery:=False
        '.UseListObject = False
    End With
End Sub

2 个答案:

答案 0 :(得分:1)

您不打开对话框选择器而是使用文件路径打开以下内容?

  Sub GetCSVList()
    ' Dim dlgOpen As FileDialog
    ' Set dlgOpen = Application.FileDialog(msoFileDialogFilePicker)
    Dim filepath As String
    filepath = "C:\test\testfile.csv"
    Application.DisplayAlerts = False
    On Error Resume Next
    Worksheets("Tickets").Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    ' With dlgOpen
    '    .AllowMultiSelect = False
    '   ''Start in
    '  .InitialFileName = "C:\test"
    ' .Show
    'End With

    'For Each fname In dlgOpen.SelectedItems
    ImportCSV filepath
'Next
End Sub

答案 1 :(得分:1)

更改你的GetCSVList子....

Sub GetCSVList()

  Application.DisplayAlerts = False
  On Error Resume Next
  Worksheets("Tickets").Delete
  On Error GoTo 0
  Application.DisplayAlerts = True

  ImportCSV "C:\test\testfile.csv"

End Sub
相关问题