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

孤街醉人 提交于 2019-12-21 09:23:54

问题


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.


回答1:


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

Declare Function GetCurrentProcessId Lib "kernel32" () As Long

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




回答2:


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

  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")))
    

Hope this helps someone




回答3:


My solution in Excel 2013: in a new module, I added the following code:

Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long

Public Sub Test()
    Debug.Print GetCurrentProcessId
End Sub


来源:https://stackoverflow.com/questions/942058/how-to-get-the-process-id-of-the-current-excel-instance-through-vba-without-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!