选项显式和macros在一个函数

我有以下代码:

Option Explicit Public Function LastWeekOfMonth() As Boolean 'finds the current date Dim CurrentDate As Date CurrentDate = CDate(ActiveSheet.Cells(FIRST_DATA_ROW, 1)) 'find filepath and filename Dim filepath As String Dim filename As String filepath = "C:\target\file\path\here\" filename = Cells(3, 4) & ".m_d.xlsm" MsgBox (filepath & filename) 'if it is the last week of the month, write a monthly report, and return true to continue with the face to face paperwork If (31 - Day(CurrentDate)) <= 7 Then 'write a monthly report Dim app As New Excel.Application Dim wsheet As New Worksheet Dim book As Excel.Workbook app.Visible = False 'Visible is False by default, so this isn't necessary Set book = app.Workbooks.Open(filepath & filename) Set wsheet = book.Worksheets("Monthly") 'Application.Run ("WriteMonthly") app.book.wsheet.Run ("WriteMonthly") book.Close SaveChanges:=True app.Quit Set app = Nothing LastWeekOfMonth = True 'if it is not, simply continue with the face to face paperwork Else LastWeekOfMonth = False End If End Function 

WriteMonthly是当前包含在目标电子表格中的macros。 在线文档说macros可以通过application.run(macros名,arg1,arg2,arg3,…)

我想从当前的电子表格中提取信息来调用特定的电子表格,并在该电子表格上运行一个macros,该macros的代码位于该电子表格上,最终生成的所有数据都将存储在该电子表格中。

这是看月份的最后几天是否已经达到的表格的一部分; 如果他们有,写一个特定的“每月”报告。

问题是这样的:

 app.book.wsheet.Run ("WriteMonthly") 

不工作,也不:

 Application.run("!WriteMonthly") 

语法是Application.Run "'WbkName'!ProcedureName"

但是,因为您正在调用的过程驻留在一个对象模块(本例中为工作表)中,所以语法也必须包含该对象的名称,例如: Application.Run "'WbkName'!ObjectName.ProcedureName"

Application.Run "'" & filename & "'!ObjectName.WriteMonthly"

ObjectNamereplace为工作表“ Monthly ”的VbModule的名称。

试试: Application.Run "'" & filename & "'!" & wsheet.CodeName & ".WriteMonthly" Application.Run "'" & filename & "'!" & wsheet.CodeName & ".WriteMonthly"

还要确保WriteMonthly程序在`Monthly'模块中没有声明为Private