WinCC VBScript: Reading Excel Cell Values via HMI Tag Events

David Krause12 min read
HMI ProgrammingSiemensTutorial / How-to
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Overview

WinCC Runtime (TIA Portal) exposes a fully featured VBScript engine that can drive any COM Automation server installed on the HMI device. The most common engineering request is to read or write a value in a Microsoft Excel worksheet (for example, the contents of cell A1) when an operator toggles a bit tag on a WinCC screen. The same technique is used to publish machine data, log recipe parameters, or import setpoints from spreadsheets prepared on the engineering station.

This reference documents the working pattern verified on WinCC Comfort/Advanced V13 SP1 with Excel 2010, and adapts it to current TIA Portal V17/V18 WinCC Runtime Advanced, Professional, and Unified PC Runtime. The MS Office Automation object model (Excel.Application) is the same across all of these — the only differences are the host (Comfort Panel, RT Advanced, RT Professional, or Unified PC) and the way the script is scheduled (event-driven on a tag change vs. cyclically).

The pattern below avoids proprietary add-ins: it uses only the Excel.Application COM interface shipped with Microsoft Office, plus the WinCC VBScript runtime. It also covers error handling, process cleanup (Quit, Nothing), and bit-edge detection so the script fires on 0→1 or 1→0 transitions, not on every RT cycle.

Prerequisites

Item Requirement Notes
TIA Portal V13 SP1 or later (V15.1, V16, V17, V18 verified) WinCC Comfort/Advanced or Professional
WinCC Runtime RT Advanced, RT Professional, or Unified PC Runtime Unified uses JavaScript — see notes below
Microsoft Excel 2010 / 2013 / 2016 / 2019 / 2021 / 365 Must be installed locally on the RT host
VBScript engine Bundled with WinCC RT Advanced/Professional No separate install required
HMI tag Boolean tag (e.g. TriggerReadExcel) Bound to a button or external bit
File path Static or dynamic via HMI tag Use \ in VBS string literals
Office bitness Match WinCC RT bitness (32-bit or 64-bit) Mismatched bitness causes 429 errors
Office Bitness: WinCC Runtime Advanced for SIMATIC Panels is delivered as a 32-bit process on Windows 10 IoT Enterprise. If you install 64-bit Office on the panel PC, COM activation will fail with error 429 ActiveX component can't create object. Install 32-bit Microsoft Office, or use the Microsoft 365 Apps (32-bit) deployment. On RT Professional and Unified PC Runtime, 64-bit Office is supported.

How WinCC Schedules VBScripts

There are three scheduling mechanisms in WinCC TIA Portal for executing a VBScript. The correct choice depends on whether the script must react to a tag change or run on a time base.

  1. Tag event (event-driven): Configure the VBScript as a "Change value" event on a specific HMI tag. The script fires whenever the tag value changes, including on rising or falling edges. This is the cleanest pattern for a button-triggered Excel read.
  2. Screen event: Trigger the script from a button's Click event using HMIRuntime.Screens("Screen_1").ScreenItems("Button_1").Click or directly call a function in the screen's VBScript module. The function is then linked to the button.
  3. Scheduler / cyclic task: Use a VBScript under Scheduled tasks to run at a fixed interval. Avoid this for Excel calls — opening the workbook every second will lock the file and consume CPU.

For the canonical "toggle a bit → read A1 from Excel" use case, use a tag change event on a dedicated boolean tag, for example TriggerReadExcel of type Bool. Edge detection inside the script is not required because the event itself only fires on value change.

Excel Object Model Used by the Script

The VBScript instantiates Excel via COM late binding, then walks the object hierarchy to reach a cell. The chain is:

Object Path Example
Application Excel.Application objExcelApp
Workbooks collection Application.Workbooks objExcelApp.Workbooks
Workbook Workbooks.Open(path) objExcelApp.Workbooks.Open("C:\\Data\\Report.xlsx")
Worksheets collection Workbook.Worksheets objWbk.Worksheets
Worksheet Worksheets(1) or Worksheets("Sheet1") objWbk.Worksheets(1)
Range / Cell Worksheet.Cells(row, col) or Worksheet.Range("A1") objWsh.Cells(1,1).Value

Cell A1 maps to Cells(1, 1), B5 to Cells(5, 2). The .Value property returns a Variant; coerce it explicitly to string, integer, or float before assigning to an HMI tag.

Step-by-Step: Read Excel Cell A1 on a Bit Trigger

Step 1 — Define the HMI tags

In the TIA Portal project tree, open HMI Tags and create:

  • TriggerReadExcel — Bool, internal or PLC-bound (DB10.DBX0.0 on an S7-1500 is typical). Connect it to a button's Press event or to a PLC handshake bit.
  • ExcelValue — WString or String of length 254, internal, to receive the cell contents.
  • ExcelStatus — Int, internal, holds the last COM error code (0 = OK).

Step 2 — Create the VBScript

Open the HMI device editor → VBScripts → right-click → Add new VBScript. Name it ReadExcel_A1. Paste the following:

' --- VBS_ReadExcel_A1 ---
' Reads cell A1 of ExcelExample.xlsx and writes the value to HMI tag "ExcelValue".
' Scheduled on tag change of "TriggerReadExcel".

Const xlUp      = -4162
Const xlDown    = -4121
Const xlToLeft  = -4159
Const xlToRight = -4161

Dim objExcelApp
Dim objWbk
Dim objWsh
Dim sPath
Dim vCell
Dim iErr

On Error Resume Next

' 1. Build path (use a network share or local SSD; do not point at the project folder)
sPath = "C:\WinCC_Data\ExcelExample.xlsx"

' 2. Start Excel hidden for background operation
Set objExcelApp = CreateObject("Excel.Application")
If Err.Number <> 0 Then
    iErr = Err.Number
    SmartTags("ExcelStatus") = iErr
    SmartTags("ExcelValue")  = "ERR: CreateObject failed"
    Err.Clear
    Exit Sub
End If
objExcelApp.Visible       = False
objExcelApp.DisplayAlerts = False
objExcelApp.ScreenUpdating = False

' 3. Open the workbook (read-only avoids lock files)
Set objWbk = objExcelApp.Workbooks.Open(sPath, False, True) ' UpdateLinks=No, ReadOnly=True
If Err.Number <> 0 Then
    iErr = Err.Number
    SmartTags("ExcelStatus") = iErr
    SmartTags("ExcelValue")  = "ERR: Open failed (" & sPath & ")"
    objExcelApp.Quit
    Set objExcelApp = Nothing
    Err.Clear
    Exit Sub
End If

' 4. Reference first worksheet and read A1
Set objWsh = objWbk.Worksheets(1)
vCell = objWsh.Cells(1, 1).Value

If Err.Number <> 0 Then
    iErr = Err.Number
    SmartTags("ExcelStatus") = iErr
    SmartTags("ExcelValue")  = "ERR: read A1 failed"
else
    SmartTags("ExcelStatus") = 0
    SmartTags("ExcelValue")  = CStr(vCell)
End If

' 5. Always close and release
objWbk.Close False
objExcelApp.Quit
Set objWsh       = Nothing
Set objWbk       = Nothing
Set objExcelApp = Nothing

On Error Goto 0

Step 3 — Bind the script to a tag event

  1. Open the HMI tag TriggerReadExcel.
  2. Switch to the Events tab.
  3. On the Change value event, click the … button and select VBS function → ReadExcel_A1.
  4. Compile the project, download to the panel or RT PC, and start Runtime.

Step 4 — Verify on a screen

Drop an I/O field bound to ExcelValue and a Bar or numeric output bound to ExcelStatus. Toggle the button (or write TRUE to the PLC bit) and watch the field populate. A status of 0 with the expected text in the I/O field confirms the round trip.

Writing Back to Excel from WinCC

The same Excel.Application automation path is used in reverse. The VBS reference example shipped in WinCC V7.x (VBS113) is fully compatible with TIA Portal V13+ — the only difference is that the runtime object model is HMIRuntime in TIA, not HMIRuntime.ActiveScreen in WinCC V7.x. The Excel portion is identical:

' --- VBS_WriteExcel_C3 ---
' Writes the value 12345 into cell C4 of ExcelExample.xlsx.
Dim objExcelApp
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = True
objExcelApp.Workbooks.Open "C:\WinCC_Data\ExcelExample.xlsx"
objExcelApp.Cells(4, 3).Value = 12345
objExcelApp.ActiveWorkbook.Save
objExcelApp.Workbooks.Close
objExcelApp.Quit
Set objExcelApp = Nothing
Read-only mode for production: For production HMIs, set objExcelApp.Visible = False and objExcelApp.DisplayAlerts = False, open the workbook with ReadOnly:=False only when you intend to write, and always call objWbk.Save before Close. Never store the workbook on a UNC path that requires user credentials; map a drive or use a local folder.

Reading a Text Field from a WinCC Screen Back to VBS

To read the value of a WinCC I/O field inside the script, use HMIRuntime.Screens and the ScreenItems collection. The exact object name is the name property of the I/O field, not its label text:

Dim objScreen, objIO
Set objScreen = HMIRuntime.ActiveScreen
Set objIO     = objScreen.ScreenItems("IO_Field_1")
Dim sVal
sVal = objIO.Text          ' current text of the I/O field
' or for a numeric I/O field:
Dim dVal
dVal = objIO.OutputValue   ' numeric value

Alternatively, bind the I/O field to an HMI tag (for example OperatorEntry) and read SmartTags("OperatorEntry") in the script. The tag-based approach is preferred because it survives screen changes, while HMIRuntime.ActiveScreen only resolves while the screen is open.

Triggering a Script When a Bit Is "Inverted"

WinCC tag events fire on every value change, not specifically on a rising edge. If you need strict rising-edge detection (for example, only react when TriggerReadExcel transitions 0 → 1), keep a memory tag and compare:

Dim bLast, bNow
bLast = Cbool(SmartTags("TriggerReadExcel_Mem"))
bNow  = Cbool(SmartTags("TriggerReadExcel"))
If (bNow = True) And (bLast = False) Then
    ' rising edge — call read routine
End If
SmartTags("TriggerReadExcel_Mem") = bNow

Bind the same VBScript to the tag's Change value event. For a more robust pattern, use a PLC-side handshake: the HMI sets a request bit, the PLC echoes back a done bit on a different tag, and the script fires on the done rising edge. This avoids race conditions in high-speed polling.

Common Error Codes and Remedies

Code Meaning Likely Cause Remedy
429 ActiveX component can't create object Office bitness mismatch or Office not installed Install 32-bit Office or run RT as 64-bit
70 Permission denied Folder is read-only, file is locked Check NTFS ACL; close Excel first
53 File not found Bad path string, escaping Use "C:\Path\File.xlsx", verify with FileSystemObject
91 Object variable not set CreateObject returned Nothing Wrap each Set with Err.Number check
1004 Application-defined / object-defined error Worksheet is chart, sheet is protected Use Worksheets(1) numeric, unprotect sheet
-2147024894 0x80070002 — file not found (HRESULT) UNC path offline, drive not mapped Test locally; map drives under the Runtime service account

Performance, Locking, and Process Hygiene

Every Workbooks.Open / Workbooks.Close cycle costs 200–600 ms on a typical panel PC and creates a temporary lock file (~\$ExcelExample.xlsx) in the folder. If the script fires on every RT cycle, you will lock yourself out of the file. Three practices eliminate this:

  1. Event-driven only. Bind the script to a tag change, never to a 100 ms cyclic schedule. If you need periodic reads, use a 1 s or longer scheduler and disable Excel's ScreenUpdating.
  2. Cache the workbook handle. Open once, hold the objWbk reference in a global, and call Refresh + Cells(...).Value for repeated reads. Close the workbook on Runtime shutdown using the End event of the project.
  3. Read-only mode. Open with ReadOnly:=True when no write is required. Excel will not create a write-lock file in this mode.

Process hygiene is critical: always objWbk.Close then objExcelApp.Quit, and Set objExcelApp = Nothing at the end. Skipping Quit leaves an orphaned EXCEL.EXE in Task Manager, which on a long-running RT will consume all available memory.

Alternatives to the Excel COM Interface

If Office cannot be installed on the runtime (common on locked-down panel PCs), or if the bitness cannot be matched, the following alternatives avoid the COM dependency entirely:

Method Direction Pros Cons
CSV via FileSystemObject Read / Write No Office; pure VBScript No formatting, no formulas, ASCII only
OPC UA / OPC DA Read / Write Native to WinCC; no file Requires OPC server
SIMATIC ProSave / ProAgent Write Direct PLC recipe handling No Excel format
WinCC Unified JavaScript Read / Write Modern TIA Portal target Different object model (HMIRuntime.UI)
SQLite / S7 data logs Write High performance, no lock External tool to open

For non-Office data exchange, a CSV file is the most reliable substitute. The same VBScript can read a CSV with FileSystemObject.OpenTextFile and parse it with Split, eliminating the dependency on Excel entirely.

Differences: WinCC V7.x vs WinCC TIA Portal

The MS Office Automation interface (the VBS code shown above) is identical in both environments. The differences are confined to the WinCC object model:

Concept WinCC V7.x WinCC TIA Portal (Advanced / Professional)
Top-level runtime object HMIRuntime HMIRuntime
Active screen HMIRuntime.ActiveScreen HMIRuntime.ActiveScreen or HMIRuntime.Screens("Name")
Tag access HMIRuntime.Tags("TagName").Read SmartTags("TagName")
Tag write HMIRuntime.Tags("TagName").Write value SmartTags("TagName") = value
VBScript editor Global Script editor in WinCC Explorer Project tree → HMI device → VBScripts
Script on tag event Tag property → Event → VBS Action Tag property → Events → Change value → VBS function

The Office Automation example in the WinCC V7.x help (VBS113) is therefore directly portable to TIA Portal as long as the HMIRuntime object references are replaced with SmartTags for tag access.

Notes for WinCC Unified (TIA V17 / V18)

WinCC Unified PC Runtime dropped VBScript in favor of JavaScript (ECMAScript 2021) and C++/Qt-based graphics. The Excel automation pattern is still available, but the syntax is different:

// WinCC Unified — read A1 from Excel
let excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
let wb = excel.Workbooks.Open("C:\\Data\\ExcelExample.xlsx");
let v  = wb.Worksheets(1).Cells(1, 1).Value;
Tags("ExcelValue").Write(v);
wb.Close(false);
excel.Quit();
excel = null;

The SmartTags collection is replaced by the Tags object inside the Unified runtime. HMIRuntime.Screens is replaced by HMIRuntime.UI.Screen (note the additional UI level). All other COM calls to Excel are identical.

Verification Checklist

  1. Set the TriggerReadExcel tag to TRUE from the PLC or via the HMI simulation. The script must execute within one RT cycle (typically 100 ms).
  2. The ExcelValue I/O field must display the cell A1 text. If the cell is numeric, the value appears as a number; if it is a date, format the I/O field as Date/Time on the HMI.
  3. The ExcelStatus tag must read 0 on success. Any other value is an error code — consult the table above.
  4. Open Task Manager on the RT host, confirm that EXCEL.EXE appears only during script execution and is gone within 1 second of Quit.
  5. Toggle the trigger ten times in succession. The ExcelValue must refresh each time and no ~$ExcelExample.xlsx lock file may remain in the folder.
  6. Reboot the RT host. The script must run identically on cold start — confirm the path is absolute and that the workbook exists before Runtime start.

Frequently Asked Questions

Why does my VBScript fail with error 429 on a SIMATIC Panel?

Error 429 means the COM activation failed. On Comfort Panels and RT Advanced (Windows 10 IoT, 32-bit), 64-bit Microsoft Office will not register as a COM server. Install the 32-bit version of Microsoft Office (or Microsoft 365 Apps 32-bit), or switch to CSV file access via FileSystemObject to avoid the dependency.

Can I read a closed Excel file from a TIA Portal HMI tag change?

Yes. The VBScript pattern in this reference opens the workbook on each trigger, reads cell A1 via objWsh.Cells(1, 1).Value, and immediately closes it. For high-frequency triggers, open the workbook once at RT start, cache the Workbook object in a global script variable, and call Workbook.Refresh for subsequent reads.

How do I detect only the rising edge of a bit tag in WinCC VBScript?

Bind the VBScript to the tag's Change value event, store the previous value in a memory tag (e.g. TriggerReadExcel_Mem), compare Cbool(SmartTags("TriggerReadExcel")) = True And Cbool(SmartTags("TriggerReadExcel_Mem")) = False, and update the memory tag at the end. This is the standard rising-edge pattern when the event itself is not edge-qualified.

Does the same script work in WinCC V7.x and TIA Portal?

The Excel COM portion is identical. Only the WinCC object model differs: use SmartTags("TagName") in TIA Portal instead of HMIRuntime.Tags("TagName").Read / .Write in WinCC V7.x. The WinCC V7.x VBS113 example can be ported verbatim if you replace the tag-access lines.

What is the recommended replacement for VBScript on WinCC Unified?

Use JavaScript with new ActiveXObject("Excel.Application"). Unified drops the SmartTags shorthand — read and write tags via Tags("TagName").Read() and Tags("TagName").Write(value). All other Excel object model calls are identical to the VBScript example.

Back to blog