2017-03-07 21 views
0

我有以下代码:显式的选项和宏在功能

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是当前包含在目标表格的宏。文档在线表示宏可以通过application.run(宏名称,arg1,arg2,arg3,...)运行

我想从当前电子表格中调用信息来调用特定的电子表格并运行宏电子表格,该宏的代码位于电子表格中,最终生成的数据将存储在该电子表格中。

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

问题是这样的:

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

不工作,也不做:

Application.run("!WriteMonthly") 
+0

尝试宏的名称前加上工作表名称程序WriteMonthly未声明为Private。你有'!WriteMonthly',但是首先添加工作簿名称。如果这不起作用,那么也许你也需要整条道路。 – BruceWayne

+0

如果您的'文件名'不包含空格,请尝试:Application.Run“C:\ path \ ... \ Book1.xls!WriteMonthly” –

+0

@ sous2817是的,它是重复的。 – bdpolinsky

回答

1

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

但是,因为你是在一个对象调用驻留的程序模块(在这种情况下的工作表)语法必须包括对象的名称,例如:Application.Run "'WbkName'!ObjectName.ProcedureName"

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

更换ObjectName与工作表MonthlyVbModule的名称。

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

还要确保在`月刊”模块

+0

您好我正在使用以下:Application.Run“'”&filepath&filename&“'!” &wsheet.Name&“.WriteMonthly”表示它不可用。我想运行位于目标工作簿中工作表每月的WriteMonthly模块中的子WriteMonthly。 – bdpolinsky

+0

得到错误1004 – bdpolinsky

+0

感谢它的工作!最终语法:Application.Run“'”&filepath&filename&“'!” &“WriteReport”&“.WriteMonthly” – bdpolinsky