2017-10-06 78 views
-1

我使用以下宏將CSV文件導入到Excel中。 宏本身工作正常,但是當我啓動宏時,我總是必須選擇要導入的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 

回答

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

更改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 
+0

一般情況下,這工作得很好 - 但我有很多單元格引用到工作表的「門票」,他們不工作了,當我刪除整個工作簿,然後導入它。我嘗試了「工作表(」Tickets「)。範圍(」A1:Z9999「)。清除」而不是你的代碼,但然後我得到工作表已經存在的錯誤。有沒有辦法做到這一點,而不會失去參考? – Andreas

+0

你在你的問題中沒有提到任何有關這方面的內容。請發佈有關該問題的另一個問題。 – jsotola