目标是使用来自第一个/主文件和调用宏的参数打开另一个Excel文件,该宏使用数据库中的数据创建1个或n个新工作表,但Excel不会在第二个文件中创建新工作表,然后是其他所有工作表逻辑失败。
您可以在下面找到两个文件的示例代码。当手动打开B文件并调用tst()sub时,这可以工作,但不能在第一个文件打开第二个文件时使用。工作簿不受保护,我使用的是MS Excel 2010。
A_file.xlsm是主文件,用户调用GetFile打开另一个文件并运行ReadParams宏。代码位于模块中。
Sub GetFile(fileName As String)
Dim filePath, par1, par2, currentUser As String
Dim targetFile As Workbook
currentUser = CreateObject("WScript.Network").UserName
filePath = "C:\Users\" & currentUser & "\Documents\Excel_APPS\"
par1 = "USE_R_one"
par2 = "some_val"
Application.ScreenUpdating = False
Set targetFile = Workbooks.Open(filePath & "B_file.xlsm")
Application.Run "'" & targetFile.Name & "'!ReadParams(" & Chr(34) & par1 & Chr(34) & ", " & Chr(34) & par2 & Chr(34) & ")"
targetFile.Activate
Application.ScreenUpdating = True
End Sub
B_file.xlsm宏:
Sub ReadParams(s_uno As String, s_duo As String)
If IsNull(s_uno) Or IsNull(s_duo) Then
MsgBox "Error occurred.", vbExclamation, "Error"
Else
MsgBox "All params are ok, new sheet is coming right after this msg"
ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Sheet_Data" '<-- THIS WON'T WORK
End If
End Sub
Sub tst()
ReadParams "USE_R", "test"
End Sub
答案 0 :(得分:1)
问题在于Application.Run...
行
其语法是
Application.Run "'b.xlsm'!ReadParams", par1, par2
您将参数连接到第一个参数