我是VBA的新手。我需要从其他位置打开现有文件,并将每个工作表保存到工作表名称(选项卡名称)名称中的不同csv文件中。我尝试过这样的事情。
Sub SplitFile()
Dim vPath As String
vPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=vPath & "\" & xWs.Name & ".csv", FileFormat:=xlCSV, CreateBackup:=False
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
这适用于当前活动的工作表,但我想在其他路径中处理另一个工作表。
我试图分配一个保存文件路径但却抛出错误的变量。
请帮帮我。在此先感谢。
答案 0 :(得分:1)
您需要创建一个工作簿变量并为其分配一个工作簿对象:
Sub SplitFile()
Dim vPath As String
Dim wb As Workbook
Dim wbPath As Variant
wbPath = Application.GetOpenFileName("Excel Files (*.xls*), *.xls*")
If wbPath = False Then Exit Sub
Set wb = Workbooks.Open(wbPath)
vPath = wb.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In wb.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=vPath & "\" & xWs.Name & ".csv", FileFormat:=xlCSV, CreateBackup:=False
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
正如您所看到的,一旦您分配了工作簿,您只需在代码中引用该代码即可。