我制作了一个模块,即一个.bas
文件,它可以完成我想在 Excel 中完成的工作。我每天必须在四个不同的文件中使用同一个模块。
现在我想要一个脚本,它可以自动将此模块与 Excel 文件链接,然后宏可以自行执行。
到目前为止我尝试过的一段代码是:
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Denied_report.csv", 0, True)
xlApp.Run "PERSONAL.XLSB!AllowedMacro"
xlApp.SaveAs
xlApp.ActiveWorkbook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
我正在使用个人文件,以便它可用于所有 Excel 文件,而不必每次都通过打开 Excel 文件来导入它!
答案1
您可能想尝试 Workbook_open 函数。该函数将在您打开 Excel 时立即运行。
Public WithEvents App As Application
Private Sub Workbook_Open()
'runs once per Excel session when Personal.xlsb is opened.
Set App = Application
MsgBox "Running Workbook_Open from Personal.xlsb"
End Sub
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
MsgBox "Running App_WorkbookOpen in " & Wb.Name
'add code you want to run upon opening each workbook here
'.....
End Sub
答案2
我尝试了这个并且成功了:
Option Explicit
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Dim strFile
strFile = "C:\De1.csv"
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open("C:\De.csv", 0, False )
xl.Application.Visible = True
xl.Application.run "PERSONAL.XLSB!Allowed_Macro"
xl.DisplayAlerts = False
xlBook.saved = True
xl.ActiveWorkbook.SaveAs strFile
xl.activewindow.close
xl.Quit
Set xlBook = Nothing
Set xl = Nothing
End Sub
我现在面临的唯一问题是,无论我对宏进行何种格式化,它们在保存后都不会保留。