2017-03-07 25 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