Excelmacros导入文本文件并覆盖工作表,而不会中断引用

我有我经常用来导入文本文件到单独的Excel工作表中的以下macros:

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$1")) .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 

…但是我想覆盖现有的工作表,如果已经使用了相同的名字。 在其他工作表中,我有工作表中的单元格的引用,将被'覆盖',所以我需要一种方法来做到这一点,而不会中断对这些单元格的引用。 任何人都知道这个好的解决scheme?

假设除查询表之外,没有任何其他信息存储在这些工作表上,请尝试以下操作:

 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 

在这种情况下,如果工作表已经存在,工作表的内容将被replace,对单元格的引用不应该改变。