简体   繁体   English

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

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

I try to export single sheet as .txt file after refreshing querytable. 我尝试在刷新querytable后将单个工作表导出为.txt文件。 I don't want to use Workbooks.Add or .Copy and .PasteSpecial method. 我不想使用Workbooks.Add.Copy and .PasteSpecial方法。 So far, I've made this: 到目前为止,我已经做到了:

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

On first loop this works great, but on second i get errors. 在第一个循环上,这个效果很好,但是在第二个循环上,我得到了错误。

Assuming Sheets(2) is part of ThisWorkbook , try the following: 假设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

Ok, I know what went wrong. 好吧,我知道出了什么问题。 Here is my original code: 这是我的原始代码:

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

Because i have ThisWorkbook.Path in loop, it changes every time I run it. 因为我有ThisWorkbook.Path循环,所以每次运行它都会更改。 Solution is simple - put ThisWorkbook.Path outsite the loop, like this: 解决方案很简单-将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

Thanks @David Zemens for help! 感谢@David Zemens的帮助!

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

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