[英]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.