2017-03-24 115 views
0

我尝试在刷新查询表后将单张导出为.txt文件。 我不想用Workbooks.Add.Copy and .PasteSpecial的方法。 到目前为止,我做了这一点:使用(Excel VBA)更新QueryTable并将结果导出为txt文件

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 

在第一循环这个伟大工程,但在第二次我得到的错误。

+1

*我收到错误*好,我们无法阅读您的想法或屏幕。你得到了什么错误,哪条线提出了它? –

+0

错误是这样的:没有文件访问。该文件可能已损坏,位于未响应的服务器上或只读。我认为在第一次循环之后,文件被保存为txt,并且代码使用变得不合理,因为xlsm不再存在('ThisWorkbook.path')。 – H3ll0

+0

你错过了一个路径分隔符,可能就是这个问题。尝试'... SaveAs ThisWorkbook.Path&Application.PathSeparator&filename&i&“.txt”...' –

回答

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 outsite循环,就像这样:

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 

感谢@大卫Zemens的帮助!

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 
相关问题