我创建了一个Excel工作簿,它将Userforms用作用户的菜单,这意味着它们不会与工作簿本身交互。通常情况下,双击即可打开,完美无缺。
现在,我想从另一个excel文件中打开此文件,并防止用户被锁定到目标工作簿(因为userform是模态的),我在新实例中打开它。
我已经研究了各种方法(其中包括https://www.mrexcel.com/forum/excel-questions/570562-vba-open-another-instant-excel-run-macro.html),在那里我找到了似乎正常工作的代码,并且还启动了Auto_Open代码(之前的尝试打开了文件,但没有启动代码)但是目标文件集成了应用程序关闭代码(由于也通过双击打开),它在关闭目标工作簿时给出了运行时错误(440),因为我认为Application.Quit命令正在中断运行 - 命令并导致错误。
我还在https://access-programmers.co.uk/forums/showthread.php?t=153101找到了一个有类似问题的人(在访问和excel之间,但我认为这个案例基本上是相同的)但是将结束代码放入调用文件的建议不起作用我,因为目标文件在一半的时间内独立于调用文件而打开。
有没有办法绕过这个或者另一种方法从另一个excel工作簿打开目标工作簿,并在打开后运行代码? 此外,如果这是一个选项,也许有一种方法可以在一个根本不涉及管理员权限的新实例中打开目标文件(无论来源)(因为我没有)?
相关代码如下:
源文件(打开目标文件):
Dim aExcel As Application
Dim wbTarget As Workbook
Dim sReturn As String
Dim sArg As String
Dim sFile As String
' File to be opened
sFile = "C:\file.xlsm"
' Neue Instance
Set aExcel = New Application
With aExcel
.Visible = True
' WB-Reference for opening of WB
Set wbTarget = aExcel.Workbooks.Open(sFile)
sArg = "'" & wbTarget.Name & "'!ModPublic.Auto_Open"
' Run Code within Targetfile (bc code does not start otherwise)
aExcel.Run sArg
' Not reached due to runtime error:
'aExcel.Quit
End With
目标文件(通过auto_open打开并执行其操作 - 之后通过userform上的[x]关闭):
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
' [x] is clicked (CloseMode = 0)
If CloseMode <> 1 Then
' deactivate Cancel
Cancel = 1
' 1 wb is open, save file and quit application
If Application.Workbooks.Count = 1 Then
ActiveWorkbook.Saved = True
Application.Quit
' more than 1 is open, save file and close wb
Else
ActiveWorkbook.Close SaveChanges:=True
End If
End If
End Sub
答案 0 :(得分:0)
可能有点解决方法,但是你可以在目标工作簿中创建一个全局变量,它指定工作簿实际上是从源工作簿打开的吗?然后在QueryClose子中使用全局变量,并在Application.Quit?
周围使用if语句