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

时间:2015-01-14 10:50:49

标签: excel vba excel-vba excel-2007 data-import

我有以下常用于将文本文件导入单独的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$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

...但如果已使用相同的名称,我想覆盖现有的工作表。在其他工作表中,我引用了工作表中将被覆盖的单元格&#39;所以我需要一种方法来做到这一点,而不会破坏对这些单元格的引用。有人知道这方面有一个很好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

假设除了查询表之外,你没有在这些表上存储任何其他信息,试试这个(我删除你的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

在这种情况下,如果片材的内容已经存在,那么它的内容将被替换,对细胞的引用不应该改变。