如何在不使用标题的情况下通过 VBA 获取当前 Excel 实例的进程 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/942058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the process ID of the current Excel instance, through VBA, without using the caption?
提问by Jason
How can I get the process ID of the current Excel instance that my VBA code is running in? I don't want to asking for it by the name in the caption, which causes problems when I have two or more Excel instances with the same caption.
如何获取运行 VBA 代码的当前 Excel 实例的进程 ID?我不想通过标题中的名称来要求它,当我有两个或更多具有相同标题的 Excel 实例时,这会导致问题。
回答by Mitchel Sellers
回答by Shreyas
As a vba n00b, some other things I did not know
作为 vba n00b,我不知道的其他一些事情
The Declare statement goes at the top. VBA will complain if the declare statement is inserted after a sub declaration
For example, this will work
Declare Function GetCurrentProcessId Lib "kernel32" () As Long Sub Update ... ... End SubBut this will not work
Sub Update ... ... End Sub Declare Function GetCurrentProcessId Lib "kernel32" () As LongHere is how we display the PID in a messagebox in vbscript
Set app = CreateObject("Excel.Application") MsgBox("Excel PID is " + CStr(app.Run("GetCurrentProcessId")))
Declare 语句位于顶部。如果在子声明之后插入声明语句,VBA 会报错
例如,这将工作
Declare Function GetCurrentProcessId Lib "kernel32" () As Long Sub Update ... ... End Sub但这行不通
Sub Update ... ... End Sub Declare Function GetCurrentProcessId Lib "kernel32" () As Long这是我们如何在 vbscript 的消息框中显示 PID
Set app = CreateObject("Excel.Application") MsgBox("Excel PID is " + CStr(app.Run("GetCurrentProcessId")))
Hope this helps someone
希望这有助于某人
回答by Corey
My solution in Excel 2013: in a new module, I added the following code:
我在 Excel 2013 中的解决方案:在一个新模块中,我添加了以下代码:
Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Public Sub Test()
Debug.Print GetCurrentProcessId
End Sub

