繁体   English   中英

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

[英]Update QueryTable and export result as txt file using (Excel VBA)

我尝试在刷新querytable后将单个工作表导出为.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

在第一个循环上,这个效果很好,但是在第二个循环上,我得到了错误。

假设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

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

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的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM