宏编译错误以拆分和保存工作表

Compile Error on Macro to Split and Save Worksheets

我在编译代码时遇到问题 - 我不确定为什么。

代码本身基于此:

https://www.extendoffice.com/documents/excel/628-excel-split-workbook.html

它将每个单独的工作表保存为一个 excel 文件,并将工作表名称作为文件名 - 这很好用。

我想更改它保存的文件名。现在它只将名称保存为 worksheetname.xls,但我希望名称为 workbookname_worksheetname.xls。这是我遇到问题的地方。我想我尝试了一些涉及 activeworkbook.name 的东西,但这给了我整个文件名,所以在保存时我得到了一个疯狂的名字,比如 workbookname.xlsx_worksheetname.xls。我开始研究如何只获取文件名,这让我找到了这些我也尝试合并的帖子:

How do I use FileSystemObject in VBA?

但是,我遇到编译错误:以下行的语法错误:

Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xFilename & "_" & xWs.Name,
    FileFormat:=39

如有必要,有人可以帮助检查和清理代码吗?有更简单的方法吗?

Sub Splitbook()
'https://www.extendoffice.com/documents/excel/1174-excel-split-data-into-multiple-worksheets-based-on-column.html
'https://www.extendoffice.com/documents/excel/628-excel-split-workbook.html
Dim xPath As String
Dim xFilename As String
'
'
Dim fso As New Scripting.FileSystemObject
xPath = Application.ActiveWorkbook.Path
xFilename = fso.GetBaseName(ActiveWorkbook.Name)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
    xWs.Copy
    Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xFilename & "_" & xWs.Name,
    FileFormat:=39
    Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

谢谢。

看来您需要线路扩展。如果你想将一行代码分成两行,你需要一个 _ 所以它应该看起来像
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xFilename & "_" & xWs.Name, _

或者把整个事情放在一行上

How to extend a formula in VBA past 1 line of code