将文本文件导入xlsm,然后覆盖sheetname(如果已存在)

时间:2013-08-13 00:13:31

标签: vba excel-vba excel

经过几个小时的谷歌搜索VB脚本失败后,我以为我会来这里。

目前我修改了一个VBA脚本,该脚本导入多个txt文件,并根据txt文件名将它们复制到XLSM文件中的新工作表中。

我想做2件事,在Google上解决{答案}答案似乎对我不起作用。

1)覆盖已存在的现有工作表---(注意:不删除它......它将链接到另一张工作表进行计算),并且

2)以空格分隔格式导入文本文件---再次解决了不玩游戏的答案。

谢谢(ps - 这里有几个类似的问题,有些问题解决了我的问题,但似乎更复杂......我追求的是尽可能简单的事情)

Sub GetSheets()
Path = "C:\test\"
Filename = Dir(Path & "*.txt")
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub

1 个答案:

答案 0 :(得分:1)

前一段时间我遇到了同样的问题,与第一个问题类似:   - 由于指向那里的引用而保留工作表

然而,我没有你的第二个约束,因此我不知道它是否匹配100%;但是我很确定你能解决它。我甚至建议您对临时工作表执行导入查询,然后使用复制粘贴宏操作将明确定义的范围移动到其最终目标

我使用导入查询解决了它。我使用“宏录制器”来做“csv import”;然后我重构了代码。

' @brief ImportFile : Opens specified file and imports contents at destination
' @param ImpFileName : Path to the file to import
' @param ImpDest : Location of the destination (must be a single cell range)

Private Sub ImportFile(ImpFileName As String, ImpDest As Range)
 With ImpDest.Worksheet.QueryTables.Add(Connection:= _
  "TEXT;" & ImpFileName, Destination:=ImpDest)
  .Name = "Import"
  .FieldNames = True
  .RowNumbers = False
  .FillAdjacentFormulas = False
  .PreserveFormatting = True
  .RefreshOnFileOpen = False
  .RefreshStyle = xlOverwriteCells
  .SavePassword = False
  .SaveData = True
  .AdjustColumnWidth = True
  .RefreshPeriod = 0
  .TextFilePromptOnRefresh = False
  .TextFilePlatform = 65001
  .TextFileStartRow = 1
  .TextFileParseType = xlDelimited
  .TextFileTextQualifier = xlTextQualifierDoubleQuote
  .TextFileConsecutiveDelimiter = False
  .TextFileTabDelimiter = False
  .TextFileSemicolonDelimiter = False
  .TextFileCommaDelimiter = True
  .TextFileSpaceDelimiter = False
  .TextFileColumnDataTypes = Array(1, 1, 1, 1)
  .TextFileTrailingMinusNumbers = True
  .Refresh BackgroundQuery:=False
 End With
 ' As the query execution does not trigger "content change event", we force triggering
 ' by editing the 1st cell's content.
 Dim MyVal As Variant
 MyVal = ImpDest.Cells(1, 1).Value
 ImpDest.Cells(1, 1) = MyVal

End Sub

您可能希望更改某些查询选项以满足您的需求。

注意:最后三行是修复错误(或看起来像一个错误的东西):查询执行不会触发裁判员的“计算”事件。