11

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.

Teamothy
  • 2,000
  • 3
  • 16
  • 26
Jason
  • 16,739
  • 23
  • 87
  • 137

3 Answers3

18

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.

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173
  • Works great; note that in VBA object modules (e.g., in a module associated with an Excel workbook), you must prefix the declaration with `Private `. – mklement0 Dec 20 '16 at 16:43
  • @mklement0 this is wrong for at least for `Excel 2010`, nevertheless if one wants to call it differently one has to wrap it in another function and thus `private` could make sense – Andreas Covidiot Sep 09 '19 at 09:21
  • @AndreasDietrich From at least 2013 on, from what I can tell, you _must_ use `Private` in _object_ modules (those associated with the workbook as a whole or a given worksheet, under "Microsoft Excel Objects" in the VBA project view, but _not_ in _code-only_ modules (under "Modules"). Additionally, in VBA 7 (not sure what version that corresponds to, but it is the case in Excel 2019), you must use the `PtrSafe` attribute (`Private Declare PtrSafe Function ...`). So, how does it work in Excel 2010 and below? – mklement0 Sep 09 '19 at 14:39
  • 1
    @mklement0 ah - thx for the clarification. I was talking then about *code-only* modules. – Andreas Covidiot Sep 10 '19 at 08:09
3

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

j0k
  • 22,600
  • 28
  • 79
  • 90
Shreyas
  • 1,410
  • 3
  • 11
  • 15
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
Corey
  • 37
  • 4