James Devine

VBA Code to Connect To Your PI Server and Output the Name

Blog Post created by James Devine on Feb 15, 2017

This simple VBA code snippet will allow you to connect to your PI Data Archive and populate a target cell with the PI Data Archive Name. You will first need to add the following "references" in your VBA Code. This is done by simply navigating to [Tools]=>[References]. This launches the "References - VBA Project" dialog box. Here you scroll and then check "PISDK 1.3 Type Library" and "PISDKCommon 1.0 Type Library".

 

Sub GetPIServerName()

   '# DECLARE YOUR VARIABLES:

    Dim piServerName As String

    Dim myPIServer As Server

    Dim thisWkBook As Workbook

    Dim aWks As Worksheet

   

    '# CONNECT TO YOUR PI SERVER:

    Set myPIServer = Servers.DefaultServer  '~ Optional: Servers("YourPIServerNameHere")

    If myPIServer.Connected = False Then

        myPIServer.Open

    End If

   

   '# GET THE PI SERVER NAME AND ACTIVATE THE RIGHT PARTS:

    piServerName = myPIServer.Name

    Set thisWkBook = ThisWorkbook

    thisWkBook.Sheets("Sheet1").Activate

    Set aWks = ActiveSheet

    aWks.Range("A1").Activate

   

    '# LOAD THE PI SERVER NAME IN THE TARGET CELL:

    ActiveCell.Value = piServerName

   

   '# CLOSE THE CONNECTION:

    myPIServer.Close

   

End Sub

Outcomes