Overview
WinCC Comfort, WinCC Advanced, and WinCC Professional (TIA Portal) runtimes expose a VBScript engine that can be triggered from HMI events (tag change, value change, click, scheduled task) or executed from a button, function key, or scheduled task configured under "Scheduled tasks." The script host supports COM automation, which means a script can launch Excel.Application as an out-of-process COM server, open a workbook, and either read cell values into HMI tags/text fields or write HMI tag values back into specific cells.
The pattern below is widely used on packaging lines, knife-head stations, recipe selection screens, and traceability stations where a maintenance engineer prefers to edit setpoints in Excel on a USB stick or a network share rather than inside the HMI project. The HMI tag (for example Golovka_nozha) acts as a discrete selector; when the operator chooses mode 1, 2, or 3, the script exchanges the corresponding cell with the workbook D:\Data.xlsx.
CreateObject("Excel.Application"). On these panels, use the file-system scripting object FileSystemObject with a CSV file as documented in the Siemens FAQ entry FAQ 59604194: Writing files with VBScript on Comfort Panels.Prerequisites
-
TIA Portal project with HMI device configured. Create the HMI tags that will exchange data with Excel. For the example below, create an internal or external tag
Golovka_nozhaof typeInt(16-bit signed) and a text tagTag_2of typeStringwith sufficient length (recommended 50..255 characters) for the imported value. -
Microsoft Excel installed on the Runtime PC for WinCC RT Advanced / Professional. Confirm the installed version with
excel.exe /?or inApps & features; Office 2016, 2019, 2021, and Microsoft 365 Apps for enterprise are all compatible with the COM interface used by the script. -
File path that the Runtime can read and write. For local files use a path on the Runtime PC such as
D:\Data\Data.xlsx. For network paths use UNC:\\PLCSVR\Recipes\Data.xlsx. Map the path to a user account that has write permission; the WinCC Runtime service normally runs underSiemensRuntimeUseror the local SYSTEM account. -
Folder access rights. Grant the Runtime service account Modify rights on the folder containing the workbook. Without write permission,
objExcelApp.ActiveWorkbook.Savereturns error 0x800A03EC or silently fails. -
Excel file is not open in protected view or in another process. If a user has the workbook open on the same machine, the script open call will succeed but the
Savecall will fail with a sharing violation. Force a single-instance writer pattern by always closing the workbook inside the script.
SmartTags() Function Reference
Inside a WinCC Runtime VBScript, every HMI tag is exposed through the SmartTags collection. The collection supports both read and write access; the tag's PLC connection direction is irrelevant because the script talks to the internal HMI tag database, not directly to the PLC.
| Operation | Syntax | Notes |
|---|---|---|
| Read tag value | value = SmartTags("TagName") |
Returns the current process value as a Variant. Implicit type conversion applies for numeric tags. |
| Write tag value | SmartTags("TagName") = value |
Triggers an immediate HMI tag update. For external tags, the value is also written to the PLC on the next acquisition cycle. |
| Check existence | Not directly available | A non-existent tag raises runtime error 451. Use On Error Resume Next with a guard if the tag may be removed during commissioning. |
| Array tags | SmartTags("ArrayTag")(i) |
Single-dimension arrays are supported. Multi-dimension arrays require manual index computation. |
| String tag length | Depends on tag length property | Configure the tag length in the TIA Portal tag table. A 1-character tag will silently truncate values to 1 char. |
For the bidirectional example the script uses an integer tag Golovka_nozha that the operator increments on the HMI through a numeric input field or stepper button. The script maps the integer value to a row index in Excel so that the operator can select recipe 1, recipe 2, or recipe 3 with a single button press.
Excel COM Object Model in WinCC
The VBScript host registers the standard Office COM type library at startup, so the Excel.Application ProgID resolves to the installed Excel instance. Each property and method call below is from the Microsoft Excel xx.0 Object Library.
| Object | Property / Method | Purpose |
|---|---|---|
Excel.Application |
Visible |
Set to True for debugging during commissioning; set to False in production to suppress the Excel window and avoid operator interference. |
Excel.Application |
Workbooks.Open(path) |
Opens the workbook and returns a Workbook object. The path must be an absolute local or UNC path. Read-only is recommended on panels by passing , , , , , , , , , , , True for the 12th argument. |
Excel.Application |
ActiveWorkbook |
Reference to the currently active workbook after Open. Used before Save and Close. |
Workbook |
Save |
Persists changes. Triggers a recalculation. If the workbook has never been saved before, supply SaveAs path instead. |
Workbook |
Close(False) |
Closes the workbook. Pass True only if you need to force-save and exit in one call. Pass False when you already called Save. |
Application |
Quit |
Terminates the Excel process if no other workbooks are open. The script must always release the COM object via Set obj = Nothing afterwards. |
Worksheet |
Cells(row, col) |
Returns a Range object. row and col are 1-based. Use the Value property to read/write. |
Writing a Tag Value into an Excel Cell
The base pattern below writes a fixed value (9999) into cell C4 of D:\12.xlsx whenever the integer tag Tag_2 equals 3. This is the canonical write pattern and corresponds to the example from the operator's working script.
If SmartTags("Tag_2") = 3 Then
Dim objExcelApp
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open "D:\12.xlsx", False, False
objExcelApp.Cells(4, 3).Value = 9999
objExcelApp.ActiveWorkbook.Save
objExcelApp.Workbooks.Close
objExcelApp.Quit
Set objExcelApp = Nothing
End If
Three enhancements tighten this script for a Runtime environment:
-
DisplayAlerts = Falsesuppresses the "Save changes?" dialog that would otherwise block the Runtime if a user has touched the workbook. - The
Opencall uses named arguments:Open(fileName, UpdateLinks, ReadOnly). The third argumentFalseopens the file in read/write mode, which is required becauseSavewill fail otherwise. - The
Set objExcelApp = Nothingrelease is the last line; the COM object goes out of scope and the WinCC script host releases its reference. Without it, the Excel process remains in the background until Runtime shuts down.
Reading an Excel Cell into an HMI Text Field
Reading mirrors the write path: open the workbook, read Cells(r, c).Value, assign the result to a string tag, and close the workbook. The script below reads row 1 column 1 (cell A1) when Golovka_nozha = 1 and writes the value into a string tag RecipeText that is bound to a text field on the screen.
Dim objExcelApp
If SmartTags("Golovka_nozha") = 1 Then
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open "D:\Data.xlsx", False, True
SmartTags("RecipeText") = CStr(objExcelApp.Cells(1, 1).Value)
objExcelApp.Workbooks.Close False
objExcelApp.Quit
Set objExcelApp = Nothing
End If
The CStr() conversion is required because the cell can be numeric, date, or boolean and the HMI string tag expects a String Variant. Without the conversion, a numeric cell would write the value as a number into the tag, which then displays as an integer in the text field rather than the formatted number the operator expects.
Bidirectional Script: Mode 1, 2 Read / Mode 3 Write
The combined script implements the operator requirement: when the integer tag Golovka_nozha equals 1 or 2, the script reads cell A1 or A2 into the text tag; when it equals 3, the script writes the current HMI counter into cell A3. The example assumes a counter tag KnifeCount of type Int that the PLC increments on each cut.
Dim objExcelApp
Dim sFile
sFile = "D:\Data.xlsx"
Select Case SmartTags("Golovka_nozha")
Case 1
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open sFile, False, True
SmartTags("RecipeText") = _
CStr(objExcelApp.Cells(1, 1).Value)
objExcelApp.Workbooks.Close False
objExcelApp.Quit
Set objExcelApp = Nothing
Case 2
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open sFile, False, True
SmartTags("RecipeText") = _
CStr(objExcelApp.Cells(2, 1).Value)
objExcelApp.Workbooks.Close False
objExcelApp.Quit
Set objExcelApp = Nothing
Case 3
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open sFile, False, False
objExcelApp.Cells(3, 1).Value = _
CLng(SmartTags("KnifeCount"))
objExcelApp.ActiveWorkbook.Save
objExcelApp.Workbooks.Close False
objExcelApp.Quit
Set objExcelApp = Nothing
End Select
Excel.Application instance. This is intentional: when the script ends, the COM object is garbage-collected and the Excel process exits. A single shared instance is faster but risks Excel staying resident between events if the script aborts unexpectedly.Robust Error Handling
A production Runtime script must survive missing files, locked workbooks, and malformed cells. Wrap the COM section in an On Error block and route failures to an HMI alarm tag so the operator can see that the exchange failed.
Dim objExcelApp
Dim sFile
Dim iRow
Dim sResult
Dim iErr
On Error Resume Next
sFile = "D:\Data.xlsx"
iRow = SmartTags("Golovka_nozha")
If iRow < 1 Or iRow > 99 Then
SmartTags("ExcelStatus") = 11 ' out-of-range row
Exit Sub
End If
Set objExcelApp = CreateObject("Excel.Application")
If Err.Number <> 0 Then
SmartTags("ExcelStatus") = 12 ' Excel not installed
Err.Clear
Exit Sub
End If
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open sFile, False, True
If Err.Number <> 0 Then
SmartTags("ExcelStatus") = 13 ' open failed
objExcelApp.Quit
Set objExcelApp = Nothing
Err.Clear
Exit Sub
End If
sResult = CStr(objExcelApp.Cells(iRow, 1).Value)
iErr = Err.Number
objExcelApp.Workbooks.Close False
objExcelApp.Quit
Set objExcelApp = Nothing
If iErr <> 0 Then
SmartTags("ExcelStatus") = 14 ' cell read failed
Err.Clear
Else
SmartTags("ExcelStatus") = 0 ' OK
SmartTags("RecipeText") = sResult
End If
Map SmartTags("ExcelStatus") to a status text list in the HMI editor (0 = OK, 11 = bad row, 12 = Excel missing, 13 = open failed, 14 = cell error) so the operator sees a meaningful message instead of a generic Runtime error.
File Path and Storage Considerations
On WinCC Runtime PCs the service account under which WinCC Runtime runs (typically SiemensRuntimeUser or a custom service account) must be granted the appropriate file-system rights. A common commissioning failure is a script that works while a developer is logged in interactively but fails when Runtime is restarted by the autologon user, because the autologon session has no write permission to D:\Data.
| Storage location | Path example | Recommendation |
|---|---|---|
| Local fixed disk | D:\Recipes\Data.xlsx |
Best performance. Use a dedicated data partition. Back up before firmware updates. |
| USB stick on Runtime PC | E:\Data.xlsx |
Detect with FileSystemObject.FolderExists("E:\") before opening. Drive letter can change after reboot. |
| Network share (server) | \\PLCSVR\Recipes$\Data.xlsx |
Use a service account with persistent credentials. Excel stalls on a network outage; add a timeout in the script (max 5 s). |
| Panel SD card (Comfort / Unified) | /media/simatic/.../Data.xlsx |
Use CSV instead of XLSX. Excel.Application is not available on these panels. |
For a network share, the COM call can hang for tens of seconds if the file server is unreachable. Wrap the Open call in a watchdog:
objExcelApp.Workbooks.Open sFile, False, True
If (Timer - t0) > 5 Then
' timeout: abort and release
objExcelApp.Quit
Set objExcelApp = Nothing
SmartTags("ExcelStatus") = 15
Exit Sub
End If
Triggering the Script from the HMI
The script must be associated with an event in the TIA Portal HMI editor. The most common triggers are:
- Value change on a tag: Configure on the tag's properties under "Events > Value change"; choose "Execute VBS function" and select the function that contains the script above. This fires the script every time the tag value changes in the Runtime.
- Click on a button: Wire the button's "Click" event to the VBS function. Suitable for operator-initiated read/write.
- Scheduled task: Use the HMI's scheduled tasks to run the function on a periodic interval (for example every 60 s) to log counters to Excel automatically.
For a value-change trigger, debounce the event by storing the previous value and only executing the script when the value actually changes. Otherwise, every PLC cycle the HMI re-acquires the tag and the script re-fires.
Reading Multi-Column Recipe Data
Real recipe files have multiple columns (setpoint 1, setpoint 2, dwell time, tolerance, etc.). Replace the single Cells(r, c) with a row read using Range and assign each column to its own HMI tag.
Dim objExcelApp
Dim ws
Set objExcelApp = CreateObject("Excel.Application")
objExcelApp.Visible = False
objExcelApp.DisplayAlerts = False
objExcelApp.Workbooks.Open "D:\Data.xlsx", False, True
Set ws = objExcelApp.ActiveSheet
SmartTags("Setpoint1") = CLng(ws.Cells(SmartTags("Golovka_nozha"), 1).Value)
SmartTags("Setpoint2") = CLng(ws.Cells(SmartTags("Golovka_nozha"), 2).Value)
SmartTags("DwellTime") = CLng(ws.Cells(SmartTags("Golovka_nozha"), 3).Value)
SmartTags("Tolerance") = CLng(ws.Cells(SmartTags("Golovka_nozha"), 4).Value)
SmartTags("RecipeName") = CStr(ws.Cells(SmartTags("Golovka_nozha"), 5).Value)
objExcelApp.Workbooks.Close False
objExcelApp.Quit
Set objExcelApp = Nothing
Create the column header row in the Excel file (A1 = Setpoint1, B1 = Setpoint2, ...) so the maintenance engineer can edit the recipe by editing cell values without touching the HMI project.
Verification
- Compile the VBS function in TIA Portal by clicking "Compile > Software (rebuild all)". Any syntax error in the script is reported with line number in the inspector window.
- Start the HMI Runtime in simulation mode (Start > Simulation) on the engineering PC. Set the
Golovka_nozhatag via the HMI tag simulation table to 1, then to 2, and confirm the text field updates with the contents of A1 and A2 respectively. - Set the tag to 3 and confirm that cell A3 in
D:\Data.xlsxcontains the current value of the counter tag. Re-open the file in Excel to verify the value persisted after the script ended. - Trigger a deliberate failure by renaming
Data.xlsxtoData.xlsx.bak. Run the script and confirm the alarm tagExcelStatusshows 13 (open failed) and the Runtime does not freeze. - On a live Runtime PC, restart the machine and confirm the autologon user can still read/write the file. If the file is on a network share, disconnect the share and re-test the timeout watchdog.
Troubleshooting Matrix
| Symptom | Likely cause | Remediation |
|---|---|---|
Runtime error 429 at CreateObject("Excel.Application")
|
Excel not installed, or DCOM permission denied for the Runtime service account. | Install a licensed Excel on the Runtime PC. Check Component Services > DCOM Config > Microsoft Excel Application > Security for the Runtime user. |
Runtime error 0x800A03EC on Save
|
Workbook opened read-only, or write permission missing. | Pass False as the third argument to Open. Grant Modify on the folder. |
| Script silently does nothing on tag change | Function is not bound to the value-change event, or tag is not configured as value-changeable. | Re-link the event to the function in the HMI editor. Confirm the tag's acquisition cycle is not zero. |
| Excel process stays open in Task Manager after script |
Set objExcelApp = Nothing missing, or Quit not called because of an error before that line. |
Move the cleanup lines to an On Error handler so they always run. |
| String tag shows integer (e.g. 1234) instead of formatted number | Missing CStr() conversion when reading a numeric cell. |
Wrap the cell read in CStr(...) before assigning to the string tag. |
Runtime freezes on Workbooks.Open
|
Network share unreachable. | Add a Timer-based watchdog; copy the file to a local path before opening. |
| Comfort Panel reports "Object not supported" on the script | Comfort Panels do not host Excel.Application COM. |
Use FileSystemObject and CSV. See FAQ 59604194 and FAQ 106501825. |
Security and Operational Notes
-
Antivirus interaction: Some antivirus suites inspect
Excel.exeon every launch and add 2..3 s of latency. Whitelist the Excel executable and the data folder to avoid Runtime timeouts. - Runtime user context: The WinCC Runtime service account should be a local administrator on the Runtime PC so DCOM launch of Excel is permitted without manual DCOMCNFG steps.
-
File locking: Always close the workbook before quitting Excel. Excel retains a write lock on the file until all handles are released; a script that crashes between
OpenandCloseleaves a~lockfile that blocks the next run. - Backups: Maintain a revisioned copy of the recipe workbook on the engineering server. The Runtime PC should pull a fresh copy at machine start, not edit the master.
- Auditing: For pharmaceutical and food applications, combine the Excel write with the WinCC audit trail so the GMP record captures the operator, timestamp, and cell value of every change.
Why does the script run on the engineering PC but fail on the Runtime PC with error 429?
Error 429 (ActiveX component can't create object) means CreateObject("Excel.Application") cannot launch the COM server. The most common cause is that Microsoft Excel is not installed on the Runtime PC, or the WinCC Runtime service account does not have launch permission for the Excel DCOM application. Install a licensed Excel on the Runtime PC and configure DCOM permissions under Component Services > DCOM Config > Microsoft Excel Application > Security.
How do I read an Excel cell into a WinCC text field on a SIMATIC Comfort Panel?
Comfort and Unified Comfort Panels do not host the Excel.Application COM object. Replace the XLSX file with a CSV file and use the FileSystemObject to read the file. Siemens documents this pattern in FAQ 59604194 for Comfort Panels and FAQ 106501825 for WinCC Advanced Runtime.
What is the difference between Workbooks.Close and Application.Quit?
Workbooks.Close closes the workbook but leaves the Excel process running. Application.Quit terminates the Excel process. For a one-shot Runtime script, call both in that order, then release the COM object with Set objExcelApp = Nothing. Skipping Quit leaves Excel.exe resident and consumes memory.
Can I trigger the script automatically when the tag value changes?
Yes. In the HMI editor, open the tag's properties, go to "Events > Value change," and select the VBS function that contains the script. The function fires each time the HMI tag value changes. To avoid re-firing on every PLC cycle, debounce by storing the previous value in a local variable and only executing the body when the value actually changes.
How do I write multiple HMI tag values into several columns of the same row?
Read the row once with a Range object and assign each cell to a separate HMI tag using SmartTags("TagName") = CStr(ws.Cells(r, c).Value). Wrap numeric reads in CLng() or CDbl() and string reads in CStr() to match the tag's data type. Use the script in the "Reading Multi-Column Recipe Data" section above as a template.