我需要将多个工作表导出到.txt文件。我希望它们保存在与工作簿相同的位置。我还需要工作表名称为.txt文件名。下面的代码是我到目前为止,但我在工作表(ws.Name)上收到调试错误。选择....任何想法?谢谢大家!
此外,我将此存储在我的个人工作簿中,以便我可以在任何已打开的文件上使用
Sub Worksheets_to_txt() '<--Saves each worksheet as a text file with the same name
Dim ws As Worksheet
Dim relativePath As String
Dim answer As VbMsgBoxResult
relativePath = ThisWorkbook.Path
answer = MsgBox("Are you sure you want to export worksheets?", vbYesNo, "Run Macro") '<--Pop up box to confirm export
If answer = vbYes Then
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
Sheets(ws.Name).Select
Sheets(ws.Name).Copy
ActiveWorkbook.SaveAs Filename:= _
relativePath & "\" & ws.Name & ".txt", _
FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close
ThisWorkbook.Activate
Next
End If
End Sub
答案 0 :(得分:2)
如果您有 2 或更多工作簿,请打开(个人和其他),然后替换:
For Each ws In ThisWorkbook.Worksheets
与
For Each ws In ActiveWorkbook.Worksheets
这样Select
就可以了。 (除非正确的工作簿也处于活动状态,否则您无法Select
表单
还要修复:
ThisWorkbook.Activate
在循环的底部
答案 1 :(得分:0)
试试这个
Sub Worksheets_to_txt() '<--Saves each worksheet as a text file with the same name
Dim ws As Worksheet
Dim relativePath As String
Dim answer As VbMsgBoxResult
relativePath = ActiveWorkbook.Path
answer = MsgBox("Are you sure you want to export worksheets?", vbYesNo, "Run Macro") '<--Pop up box to confirm export
If answer = vbYes Then
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each ws In ActiveWorkbook.Worksheets
ws.Select
ws.Copy
ActiveWorkbook.SaveAs Filename:= _
relativePath & "\" & ws.Name & ".txt", _
FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close
ActiveWorkbook.Activate
Next
End If
End Sub