我在excel表中添加了一个按钮,并在该按钮的vba窗口中添加了以下代码。现在,当我单击此按钮时,即当我运行代码时,它以pdf格式保存excel表格,其名称取自单元格no H8并将其保存为M:\格式。此外,它还以M:\ formats \ excels格式保存.xlsx格式的相同Excel工作表。但问题是,当我运行代码时,它关闭了excel表,我在其中添加了代码并打开了代码保存的文件。例如,我制作了abc.xlsm excel表并在vb窗口中添加了代码,现在xyz写在abc.xlsm excel表中的单元格no h8中,现在当我运行代码时它关闭abc.xlsm并且所有代码都显示在xyz.xlsx excel表。我想它应该只保存xlsx格式的文件它必要的位置。它不应该关闭基本文件(在上面的例子中是abc.xlsx),不应该打开保存的文件(在上面的例子中是xyz.xlsx)。此外,我希望保存的文件(上例中的xyz.xlsx)不应包含任何vba编码。换句话说,它应该像基本文件的备份副本(在上面的例子中是abc.xlsx)。请帮助我根据需要修改这些代码。我将非常感谢你。谢谢
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
strBasePath = "M:\formats\excels\"
strFileName = Range("H8")
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName,
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
答案 0 :(得分:1)
这是代码,只有两处小改动。这两组新线都有评论" New"在他们面前。
还要稍微整理一下错误处理程序。
它的工作方式是:
将当前工作簿的文件名存储在变量&#;; strMasterWorkbookFilename'
PDF文件由'导出'创建。工作表。
然后将Excel工作表另存为XLSX。这有效地关闭了#39;原始工作簿。
3.1按钮("按钮8")将从新的XLSX工作表中删除,工作簿将再次保存。
注意 - 保存为XLSX将从保存的文件中删除宏代码。宏将留在主要'主要'文件。
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
' NEW
Dim strMasterWorkbookFilename As String
strMasterWorkbookFilename = ThisWorkbook.FullName
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbook
wsThisWorkSheet.Shapes("Button 8").Delete
ActiveWorkbook.Save
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
' NEW
Workbooks.Open strMasterWorkbookFilename
Workbooks(strFileName).Close SaveChanges:=False
exitHandler:
Exit Sub
errHandler:
MsgBox "Error Saving file. The error is " & vbCrLf & Chr(34) & Err.Description & Chr(34)
Resume exitHandler
End Sub
感谢您将此作为新问题发布。如果我继续修改第一个问题中的原始代码,那么对于阅读原始帖子的任何其他人来说都不会有用。