如何在不使用标题的情况下通过 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:48:54  来源:igfitidea点击:

How to get the process ID of the current Excel instance, through VBA, without using the caption?

excelvbapid

提问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

You can use this method to get the current process id.

您可以使用此方法获取当前进程 ID。

Declare Function GetCurrentProcessId Lib "kernel32" () As Long

This pagehas a good overview of exactly how you can do it in various versions of excel.

这个页面很好地概述了如何在各种版本的 excel 中做到这一点。

回答by Shreyas

As a vba n00b, some other things I did not know

作为 vba n00b,我不知道的其他一些事情

  1. 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 Sub
    

    But this will not work

    Sub Update
      ...
      ...
    End Sub
    
    Declare Function GetCurrentProcessId Lib "kernel32" () As Long
    
  2. Here is how we display the PID in a messagebox in vbscript

    Set app = CreateObject("Excel.Application")
    MsgBox("Excel PID is " + CStr(app.Run("GetCurrentProcessId")))
    
  1. Declare 语句位于顶部。如果在子声明之后插入声明语句,VBA 会报错

    例如,这将工作

    Declare Function GetCurrentProcessId Lib "kernel32" () As Long
    
    Sub Update
      ...
      ...
    End Sub
    

    但这行不通

    Sub Update
      ...
      ...
    End Sub
    
    Declare Function GetCurrentProcessId Lib "kernel32" () As Long
    
  2. 这是我们如何在 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