I am using Excel 2003. The macro below opens a workbook "Book1.xls" and runs a simple macro "Opening" which in this case is just a simple message box for test purporses. This macro will fail if the workbook is named "Book-1.xls".
I even tested with the workbook in subdirectories which had dashes in the folder name, and the macro works as long as the file name itself does not have a dash.
Sub RunMacro_NoArgs()
'Macro purpose: Use the application.run method to execute
'a macro without arguments from another workbook
Dim PathToFile As String, _
NameOfFile As String, _
wbTarget As Workbook, _
CloseIt As Boolean
Dim namelength As Integer
'Set file name and location. You will need to update this info!
NameOfFile = "Book1.xls"
PathToFile = "C:\Documents and Settings\user\Desktop"
'Attempt to set the target workbook to a variable. If an error is
'generated, then the workbook is not open, so open it
On Error Resume Next
Set wbTarget = Workbooks(NameOfFile)
If Err.Number <> 0 Then
'Open the workbook
Err.Clear
Set wbTarget = Workbooks.Open(PathToFile & "\" & NameOfFile)
CloseIt = True
End If
'Check and make sure workbook was opened
If Err.Number = 1004 Then
MsgBox "Sorry, but the file you specified does not exist!" _
& vbNewLine & PathToFile & "\" & NameOfFile
Exit Sub
End If
On Error GoTo 0
Application.Run (wbTarget.Name & "!ThisWorkbook.Opening")
If CloseIt = True Then
'If the target workbook was opened by the macro, close it
wbTarget.Close savechanges:=False
Else
'If the target workbook was already open, reactivate this workbook
ThisWorkbook.Activate
End If
End Sub
Code originally from VBA Express Portal
Bookmarks