上面的答案可能会与活动工作簿以外的其他工作簿一起使用,这是我需要做的。这是我用的
在启动时,确保实例中的工作簿是单独的:
Private Sub Workbook_Open()
If Application.Workbooks.Count > 1 Then 'check if there's >1 open wb's in this instance
If MsgBox("This workbook will be moved to a new instance of Excel," & vbLf & _
"so as to not affect performance of your other workbooks.", _
vbOKCancel + vbInformation + vbDefaultButton1 + vbMsgBoxSetForeground) _
= vbCancel Then Exit Sub
Debug.Print Application.Hinstance, "Moving wb to new instance."
OpenInNewInstance
Debug.Print Application.Hinstance, "Moved wb to new instance."
Else
Debug.Print "This wb is in it's own instance. (#" & Application.Hinstance & ")"
End If
End Sub
Sub OpenInNewInstance()
With ThisWorkbook
.Save 'save workbook before making it read-only
.ChangeFileAccess xlReadOnly 'make this wb read-only (so the other isn't)
Shell ("excel.exe /x """ & .FullName & """") 'open current wb in new instance
.Close 'close this workbook
End With
End Sub
此代码放在该ThisWorkbook
模块,从而使工作簿时立即打开它检查是否它是唯一在这种情况下打开工作簿,如果没有:
- 保存当前工作簿
- 将当前wb设置为只读(以防止出现第二个副本)
- Shell到命令提示符以在新实例中打开Excel(使用Excel的
/x
命令行开关),从而加载当前工作簿的另一个实例
- 关闭当前工作簿
如有必要,可以在打开新实例时使用自定义命令行将指令等转移到新实例。您还可以考虑为新实例隐藏应用程序窗口的优缺点。