【问题标题】:Excel macro to import text file and overwrite worksheet without breaking referencesExcel 宏用于导入文本文件并覆盖工作表而不破坏引用
【发布时间】:2015-01-15 01:28:10
【问题描述】:

我有以下宏,我经常使用它来将文本文件导入单独的 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

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

【问题讨论】:

  • 如果你覆盖了那些工作表,保留这些引用有什么意义?你只是在附加内容吗?
  • 文本文件中的数据是“更新”值。这实际上是使用文本文件中的数据“刷新”工作表。
  • 也许您应该尝试仅添加新信息。这样您就可以保留旧工作表、对它的引用并仍然对其进行更新。我得承认我不确定你的代码是做什么的——从来没有使用过查询表——但如果你可以提取新信息,我相信有一种方法可以轻松附加它。
  • 这就是为什么我想问问 SA 的聪明人是否知道一个好的解决方案;)
  • 查看类似问题Excel Interop - How to change named range。为引用使用命名范围使数据更新更容易

标签: vba excel excel-2007 data-import


【解决方案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

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

【讨论】:

  • 我得到'无法将工作表重命名为与另一个工作表、引用的对象库或 Visual Basic 引用的工作簿相同的名称'指向行'ws.Name = strFile2'
  • 抱歉,现在试试。
  • 不用担心。现在我得到'目标范围不在创建查询表的同一个工作表上'......也许我必须规定当前工作表??
  • 我添加了 ws.Activate 行并编辑了参考。查询表的所有其他示例都以这种方式引用它们,因此在这种情况下可能需要它。这是一些反复试验,但我无法为查询表设置测试表以确保检查。
猜你喜欢
  • 2013-10-30
  • 2016-06-14
  • 1970-01-01
  • 2012-04-15
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多