Visual Basic(Excel)通过1按钮运行2个宏?

时间:2017-12-20 23:54:24

标签: excel vba excel-vba

您好我有一个按钮可将我的电子表格导出为PDF。

我希望该按钮导出文档并将其保存在名为" Excel Calculator"的文件夹中。目前我只能获取要创建的文件夹或要导出的文档。我不知道如何一次运行这两个命令,因此文档导出并保存在excel计算器文件夹中。

另外,如何更改文件路径,而不是像我指定的那样进入D:\,它会找到用户"我的文档"文件夹中。

Sub GetFilenameForPDF()
 Dim strFileName As String, strB1 As String, strWorksheet As String


 strB1 = Range("B1").Value
 strWorksheet = ActiveSheet.Name
 strFileName = strB1 & " " & strWorksheet & " " & Format(Date, "DD-MM-YYYY")


End Sub

Sub NewFolder()

 Dim fso As FileSystemObject
 Dim folderName As String

 Set fso = New FileSystemObject
 folderName = "D:\Excel Calculator"
 If fso.FolderExists(folderName) = False Then
     fso.CreateFolder folderName
 End If

 Dim strFileName As String, strB1 As String, strWorksheet As String
 strB1 = Range("B1").Value
 strWorksheet = ActiveSheet.Name
 strFileName = folderName + "\" + strB1 & " " & strWorksheet & " " & 
 Format(Date, "DD-MM-YYYY")

 ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
     "D:\" & strFileName & ".pdf", _
     Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
 End Sub

 Sub SaveToPDF()

 Dim strFileName As String, strB1 As String, strWorksheet As String
 strB1 = Range("B1").Value
 strWorksheet = ActiveSheet.Name
 strFileName = strB1 & " " & strWorksheet & " " & Format(Date, "DD-MM-YYYY")

 ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
     "D:\" & strFileName & ".pdf", _
     Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
     :=False, OpenAfterPublish:=True
     End Sub

1 个答案:

答案 0 :(得分:0)

您可以按顺序调用多个宏。例如,如果将按钮链接到宏fullSequence,则可以先运行文件夹的创建,然后将文件导出到该文件夹​​中:

Sub fullSequence()
    createFolder '<-- call macro 1
    exportFile '<-- call macro 2
End Sub

在您的具体情况下,您只需要修改宏NewFolder的代码:

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
     "D:\" & strFileName & ".pdf", _
     Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True

......对此:

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
     folderName & "\" & strFileName & ".pdf", _
     Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True

...以便将folderName(您已有文件夹路径的位置)包含在导出Filename参数中。