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

时间:2016-10-27 18:38:06

标签: vba split macros save worksheet

我在编写代码时遇到问题 - 我不确定原因。

代码本身就是基于此:

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? File name without extension name 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
'https://stackoverflow.com/questions/3233203/how-do-i-use-filesystemobject-in-vba/3236348#3236348
'https://stackoverflow.com/questions/27923926/file-name-without-extension-name-vba
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

谢谢。

1 个答案:

答案 0 :(得分:0)

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

或将整个事情放在一行

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