【发布时间】: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