如何在替换现有工作表的工作簿中加载CSV?

时间:2017-10-06 02:38:23

标签: excel vba excel-vba

我有以下宏将CSV文件作为新工作表导入,称为“工单”。当此文件存在时,我收到运行时错误。有没有办法只覆盖现有文件,如果它已经存在?

Sub GetCSVList()
Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogFilePicker)
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 个答案:

答案 0 :(得分:0)

在最后添加新工作表后,尝试删除任何名为“Tickets”的现有工作表,然后将新工作表重命名为“Tickets”:

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

On Error Resume Next将忽略在没有任何名为“Tickets”的现有工作表时可能出现的错误。这有点懒,但这几乎是Worksheet.Delete方法产生的唯一错误,所以你可以逃脱它。

不要“On Error Resume Next”在编程中忽略其他类型的错误!