我有一个宏打开一个对话框来打开文件,一旦该文件打开,我希望能够在打开的文件上使用另一个宏。
这是浏览文件按钮代码:
Sub Open_Workbook_FileDialog()
Dim strFileToOpen As String
strFileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="Excel Files *.xlsx* (*.xlsx*),")
If strFileToOpen = "" Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Workbooks.Open Filename:=strFileToOpen
End If
End Sub
因此,上面的宏允许我打开一个文件,一旦打开该文件,我希望能够在该打开的文件上使用另一个宏(从相同的'浏览文件'工作簿或其他文件引用工作簿)。有没有办法让这种情况发生?
提前致谢。
答案 0 :(得分:0)
您希望从已打开的工作簿中运行MACRO,但是您已将GetOpenFilename
过滤为仅显示.xlsx
个文件,并且您需要打开.xlsm
个文件(因为Excle文件包含其中的MACRO保存为.xlsm
)。
所以你原来的一行:
strFileToOpen = Application.GetOpenFilename (Title:="Please choose a file to open", FileFilter:="Excel Files *.xlsx* (*.xlsx*),")
在以下代码中修改为:
strFileToOpen = Application.GetOpenFilename (Title:="Please choose a file to open", FileFilter:="Excel Files *.xlsm* (*.xlsm*),")
Sub Open_Workbook_FileDialog()
Dim strFileToOpen As String
Dim WB As Workbook
strFileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If strFileToOpen = "" Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Set WB = Workbooks.Open(strFileToOpen)
Dim MacroName As String
' just for example >> modify to your MACRO name
MacroName = "main1"
Application.Run "'" & WB.Name & "'!" & MacroName
End If
End Sub