启用宏的工作簿保存到错误的文件夹

时间:2015-10-26 14:31:12

标签: excel vba path save directory

当我使用以下代码时:

  1. 保存启用宏的工作簿
  2. 与打开的工作簿相同的文件夹
  3. 它会使用错误的名称和桌面保存文件:

    Sub Save_New_MacroEnabledFile()
    
        Dim thisWb As Workbook
    
        Set thisWb = ActiveWorkbook
        Worksheets("Sheet_with_VBA_Button").Activate
        ActiveWorkbook.SaveAs Filename:=thisWb.Path & Sheets("Sheet_with_NewFile's_Name").Range("A2"), FileFormat:= _
            xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
            ReadOnlyRecommended:=False, CreateBackup:=False
    
    End Sub
    

    我做错了什么?

1 个答案:

答案 0 :(得分:1)

在创建新文件路径时,您没有添加斜杠。

您拥有此文件的文件夹可能位于桌面上而没有斜杠,只需将文件名附加到文件夹名称即 文件夹是:

C:\Users\Antoine\Desktop\Folder

并且在没有斜线的情况下附加文件名之后就像是:

C:\Users\Antoine\Desktop\Folderfilename.xlsx

试试这段代码:

Sub Save_New_MacroEnabledFile()
    Dim thisWb As Workbook
    Dim fileName As String

    Set thisWb = ActiveWorkbook
    Worksheets("Sheet_with_VBA_Button").Activate

    Application.DisplayAlerts = False
    fileName = thisWb.Path & "\" & Sheets("Sheet_with_NewFile's_Name").Range("A2") & VBA.IIf(Right(fileName, 5) = ".xlsm", "", ".xlsm")

    ActiveWorkbook.SaveAs fileName:=fileName, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
        ReadOnlyRecommended:=False, CreateBackup:=False
    Application.DisplayAlerts = True

End Sub