调试Excel VBA ActiveWorkbook.SaveAs

时间:2016-02-11 18:23:15

标签: excel vba excel-vba

我不确定为什么我的VBA代码片段不起作用 - 我希望有人可以提供帮助。

我只是尝试将ActiveWorkbook.SaveAs作为更大模块的一部分来执行,但它出错了。

以下是发生错误的代码段:

LdrLastName = Right(wbCleaner.Sheets("Import Information").Range("$A$2"), Len(wbCleaner.Sheets("Import Information").Range("$A$2")) - Len(Left(wbCleaner.Sheets("Import Information").Range("$A$2"), LstNameSpacePos)))
ExptdQBInitialFileName = LdrLastName & " " & wbCleaner.Sheets("Import Information").Range("$D$2") 'produces "LastName AccountCode"

'ExptdQBFileName MsgBox's the full file path and file name (i.e. C:/Folder/Filename.xlsx)
ExptdQBFileName = Application.GetSaveAsFilename(InitialFileName:=ExptdQBInitialFileName, FileFilter:="QB Export File *.xlsx (*.xlsx),")

If ExptdQBFileName <> "" And ExptdQBFileName <> "False" Then
    ActiveWorkbook.SaveAs Filename:=ExptdQBFileName, _
        FileFormat:=xlOpenXMLWorkbook, _
        Password:="", _
        WriteResPassword:="", _
        ReadOnlyRecommended:=False, _
        CreateBackup:=False
End If

错误突出显示If / End If语句中的所有内容。我之前使用过此代码没有问题。我在哪里错了?

3 个答案:

答案 0 :(得分:2)

只是为了分享,这本工作簿和活动工作簿之间有所不同 http://datapigtechnologies.com/blog/index.php/thisworkbook-vs-activeworkbook/

答案 1 :(得分:1)

文件格式52是xlOpenXMLWorkbookMacroEnabledxlsm文件。如果您保存为.xlsx文件,我认为您想要的文件格式是xlOpenXMLWorkbook,它会转换为51。

使用枚举而不是整数是有帮助的:

LdrLastName = Right(wbCleaner.Sheets("Import Information").Range("$A$2"), Len(wbCleaner.Sheets("Import Information").Range("$A$2")) - Len(Left(wbCleaner.Sheets("Import Information").Range("$A$2"), LstNameSpacePos)))
ExptdQBInitialFileName = LdrLastName & " " & wbCleaner.Sheets("Import Information").Range("$D$2") 'produces "LastName AccountCode"

ExptdQBFileName = Application.GetSaveAsFilename(InitialFileName:=ExptdQBInitialFileName, FileFilter:="QB Export File (*.xlsx), *.xlsx,")

If ExptdQBFileName <> "" And ExptdQBFileName <> "False" Then
    ActiveWorkbook.SaveAs Filename:=ExptdQBFileName, _
        FileFormat:=xlOpenXMLWorkbook, _
        Password:="", _
        WriteResPassword:="", _
        ReadOnlyRecommended:=False, _
        CreateBackup:=False
End If

http://www.rondebruin.nl/win/s5/win001.htm

答案 2 :(得分:1)

我不知道为什么,但解决方案是改变

ActiveWorkbook.("QB Export File").SaveAs

ThisWorkbook.Sheets("QB Export File").SaveAs

感谢user2851376分享以下链接,比较ThisWorkbook与ActiveWorkbook http://datapigtechnologies.com/blog/index.php/thisworkbook-vs-activeworkbook/