Excel 导入文本文件并覆盖工作表而不破坏引用的宏

Excel macro to import text file and overwrite worksheet without breaking references

我经常使用以下宏将文本文件导入单独的 excel 工作表:

Sub ImportManyTXTs()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("C:\location\of\folder\with\textfiles\*.txt")
Do While strFile <> vbNullString

strFile2 = Replace(strFile, ".txt", "")

Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
    "TEXT;" & "C:\location\of\folder\with\textfiles\" & strFile, Destination:=Range("$A"))
    .Name = strFile
    .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 = True
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = True
    .TextFileColumnDataTypes = Array(1, 1, 1)
    .TextFileFixedColumnWidths = Array(7, 9)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
ws.Name = strFile2
strFile = Dir
Loop
End Sub

...但如果已使用相同的名称,我想覆盖现有的工作表。在其他工作表中,我引用了工作表中的单元格 'overwritten' 因此我需要一种方法来执行此操作而不破坏对这些单元格的引用。有人知道解决这个问题的好方法吗?

假设除了查询表之外,您没有在这些 sheet 上存储任何其他信息,试试这个(我删除了 space 的 with 语句):

Sub ImportManyTXTs()
Dim strFile As String
Dim Sht As Worksheet
Dim ws As Worksheet
strFile = Dir("C:\location\of\folder\with\textfiles\*.txt")
Do While strFile <> vbNullString

strFile2 = Replace(strFile, ".txt", "")

For Each Sht in Worksheets
    If Sht.Name = strFile2 Then
        Sht.Cells.ClearContents
        Set ws = Sht
    End If
Next Sht
If ws Is Nothing Then
    Set ws = Sheets.Add
    ws.Name = strFile2
End If
ws.Activate

With ActiveSheet.QueryTables.Add(Connection:= _
    'YourStuffHere
End With

strFile = Dir
Loop
End Sub

在这种情况下,sheet 的内容将被替换(如果它已经存在),对单元格的引用不应更改。