使用(Excel VBA)更新QueryTable并将结果导出为txt文件

时间:2017-03-24 18:17:18

标签: vba excel-vba excel

刷新查询表后,我尝试将单页导出为.txt文件。 我不想使用Workbooks.Add.Copy and .PasteSpecial方法。 到目前为止,我已经做到了:

Do Until i = 5
  With Sheets(2).QueryTables(1)
     .Refresh BackgroundQuery:=False
  End With

  Sheets(2).SaveAs ThisWorkbook.path & filename & i & ".txt", _
  FileFormat:=xlTextMSDOS, CreateBackup:=False

i = i + 1
Loop

在第一个循环中,这很有效,但在第二个循环中我得到错误。

2 个答案:

答案 0 :(得分:0)

假设Sheets(2)属于ThisWorkbook,请尝试以下操作:

Dim sep As String
sep = Application.PathSeparator

With ThisWorkbook
    Do Until i = 5
      .Sheets(2).QueryTables(1).Refresh BackgroundQuery:=False
      .Sheets(2).SaveAs .path & sep & filename & i & ".txt", _
           FileFormat:=xlTextMSDOS, CreateBackup:=False

      i = i + 1
    Loop
End With

答案 1 :(得分:0)

好的,我知道出了什么问题。这是我的原始代码:

Sub test()
Dim filename As String
Dim i As Integer
filename = "test_txt"
i = 0
Do Until i = 5
  With Sheets(2).QueryTables(1)
     .Refresh BackgroundQuery:=False
  End With

  Sheets(3).SaveAs ThisWorkbook.Path & "\FOLDER\" & filename & i & ".txt", _
  FileFormat:=xlTextMSDOS, CreateBackup:=False

i = i + 1
Loop
End Sub

因为我在循环中有ThisWorkbook.Path,所以每次运行它都会改变。解决方案很简单 - 将ThisWorkbook.Path放在循环外,如下所示:

Sub test()
Dim filename As String
Dim saveloc as String
Dim i As Integer
filename = "test_txt"
saveloc = ThisWorkbook.Path & "\FOLDER\"
i = 0
Do Until i = 5
  With Sheets(2).QueryTables(1)
     .Refresh BackgroundQuery:=False
  End With

  Sheets(3).SaveAs saveloc & filename & i & ".txt", _
  FileFormat:=xlTextMSDOS, CreateBackup:=False

i = i + 1
Loop
End Sub

感谢@David Zemens的帮助!