Reading Tags from CSV Files in WinCC Runtime via VBScript
WinCC Runtime (TIA Portal) exposes a VBScript host in which user scripts can read external CSV or TXT files, parse the values, and write them directly into HMI/PLC tags. This article documents the two field-proven methods, the FSO (FileSystemObject) line-by-line reader and the ADODB OLE DB provider, and ties them to Siemens' official scripting model, diagnostic utilities, and the WinCC Unified CSV export path introduced in TIA Portal V17 and refined in V21.
1. Overview
On a WinCC Runtime PC station (RT Professional, RT Advanced, or Unified), tags in the tag management are normally sourced from a connected PLC (S7-1200, S7-1500, S7-300/400) or from internal tag memory. In some machine applications the engineering requirement is the opposite: WinCC must consume data generated by an external system, a MES export, a recipe file, a barcode scanner log, or a third-party tool, where that data is delivered as a comma- or semicolon-separated text file on the local file system.
Because WinCC Runtime is built on a Windows process (CCEServer / CCAgent) and embeds a VBScript engine, any standard Windows COM automation object is available to a script. The two COM libraries most often used for CSV consumption are:
| COM Object | Library | Strengths | Limits |
|---|---|---|---|
| Scripting.FileSystemObject | Microsoft Scripting Runtime (scrrun.dll) | Lightweight, no driver setup, full control over delimiter and parsing | Manual line-by-line parsing, no SQL filtering |
| ADODB.Connection / ADODB.Recordset | Microsoft ActiveX Data Objects (msado*.dll) | SQL-like query against the CSV via Jet/ACE OLE DB provider | Requires Schema.ini, 32-bit provider on 32-bit RT, locale pitfalls with decimal separator |
2. Prerequisites
- WinCC Runtime installed on the PC station (RT Professional V13 SP1+ or RT Advanced V13 SP1+; for the Unified workflow described in section 7, TIA Portal V17+ with the WinCC Unified PC Runtime installed).
- The HMI tag that will receive the imported value must exist in the project tag table. External tags pointing to a non-existent internal variable will produce a
Tag not foundruntime error. - The CSV/TXT file must be reachable from the WinCC Runtime user account (default: the user that started CCEServer / CCAgent). A UNC path requires read permission for that account; a local path under the project folder is preferred.
- The
Filenametag configured in the tag table should be an internal String tag, used by the script to receive the target file path at runtime. - VBScript debugging should be enabled. In TIA Portal, under Project > Runtime settings > Scripts, enable Activate global script diagnostics so that
HMIRuntime.Traceoutput is captured.
apdiag.exe via a USB service connection or export the trace to file as described in section 6.
3. Architecture: How the Script Talks to the Tag System
The WinCC Runtime VBScript host exposes a single root automation object, HMIRuntime, plus optional HMIRuntime aliases depending on the TIA version. The relevant child collections are:
| Object | Type | Purpose |
|---|---|---|
| HMIRuntime.Tags | Collection | Access to all configured HMI tags by name |
| HMIRuntime.Trace | Method | Writes a string to the diagnostics output window |
| SmartTags | Helper | Convenience accessor used by some HMI controls |
| HMIRuntime.Screens | Collection | Screen switching and screen-scoped tags |
Each tag object returned by HMIRuntime.Tags("Name") exposes .Value (read/write), .Read, .Write, .Name, .QualityCode, and .LastError. The .Value property is a Variant; conversions to CStr, CDbl, CLng must be explicit to avoid type-mismatch runtime errors.
4. Method 1 - Scripting.FileSystemObject (FSO)
The FSO approach is the simplest and is the recommended starting point when the CSV has a known, stable column order and a single delimiter. The reference script below is the canonical example that has shipped across multiple Siemens Knowledge Base and forum threads and remains the baseline pattern in V13 SP1 through V17 projects.
4.1 Reference script
Sub OnClick(Byval Item)
Dim tagName, tagValue, tagFilename
Dim strFilename, strLine, arrItems
Dim fso, objFile, objTag
Set tagFilename = HMIRuntime.Tags("Filename")
Set fso = CreateObject("Scripting.FileSystemObject")
strFilename = tagFilename.Read
If fso.FileExists(strFilename) Then
HMIRuntime.Trace "VB-Script: read file: " & strFilename & vbCrLf
Set objFile = fso.OpenTextFile(strFilename, 1) ' 1 = ForReading
Do
strLine = objFile.ReadLine
arrItems = Split(strLine, ";", -1, 1)
tagName = CStr(arrItems(0))
tagValue = CDbl(arrItems(1))
HMIRuntime.Trace tagName & " Value: " & tagValue & vbCrLf
Set objTag = HMIRuntime.Tags(tagName)
objTag.Value = tagValue
objTag.Write
Loop Until objFile.AtEndOfStream
objFile.Close ' close AFTER the Else branch falls through
Else
HMIRuntime.Trace "File: " & strFilename & " not found!" & vbCrLf
End If
End Sub
4.2 Step-by-step explanation
-
Get the file path. The internal tag
Filenameis read withtagFilename.Read. The full path can be a local absolute path (D:\Project\Tags.csv) or a UNC path (\\MES-SRV\Export\Tags.csv). -
Create the FSO.
CreateObject("Scripting.FileSystemObject")instantiates the Microsoft Scripting Runtime. The reference is held infsoand is used only forFileExistsandOpenTextFile. -
Verify the file.
fso.FileExists(strFilename)returns False for directories and for files the WinCC user has no read access to. The Else branch logs toHMIRuntime.Traceand exits the Sub. -
Open for reading.
OpenTextFile(path, 1)opens the file in ForReading mode (Unicode or ASCII, depending on the file's BOM).OpenAsTextStreamis an alternative for an existing File object. -
Read and parse.
objFile.ReadLinereturns a line without the newline character.Split(strLine, ";", -1, 1)uses-1, 1for the limit and compare arguments: -1 means "return all substrings", and 1 means TextCompare (case-insensitive), which is irrelevant for the delimiter but harmless. -
Type-cast values.
CStrandCDblare required because the FSO returns Variants.CDblhonours the system locale: on a German engineering stationCDbl("3,14")returns 3.14, butCDbl("3.14")returns 314 because the decimal separator is locale-specific. See section 8. -
Write to the HMI tag. The
.Value = tagValueassignment updates the in-memory copy;.Writecommits the value to the runtime database so connected PLCs / consumers see the new value. -
Close the file.
objFile.Closemust be reached on the success path. TheLoop Until objFile.AtEndOfStreamform means the loop body executes at least once, so always close the file after the loop ends.
4.3 Common file-format considerations
| CSV trait | Detection | Recommended change |
|---|---|---|
| Comma delimiter | Inspect the file with a text editor | Replace Split(strLine, ";", -1, 1) with Split(strLine, ",", -1, 1)
|
| Tab delimiter | Often generated by Excel "Save as TXT (Tab)" | Use vbTab as the Split delimiter |
| Header row | First row contains alphabetic names | Call objFile.SkipLine once before the loop |
| CRLF line endings | Default for Windows; ReadLine handles them |
No change |
| LF-only line endings | Some Linux exports |
ReadLine still works; verify with a Hex editor (0x0A only) |
| Quoted strings containing the delimiter | CSV from Excel / MES | Switch to the ADODB method (section 5) for proper RFC 4180 handling |
5. Method 2 - ADODB Connection to the CSV
When the CSV file is large, has many columns, or contains quoted fields with embedded delimiters, the FSO loop becomes fragile. WinCC VBScript can host the standard ADODB stack, allowing the script to treat the CSV directory as an OLE DB data source and execute SQL queries against it.
5.1 Required file: Schema.ini
The Microsoft Text Driver (ACE.OLEDB or JET.OLEDB) reads column types from a Schema.ini file placed in the same directory as the CSV. Example:
[Tags.csv]
Format=Delimited(;)
CharacterSet=ANSI
ColNameHeader=True
Col1=TagName Char Width 64
Col2=TagValue Double
Col3=Timestamp Char Width 30
5.2 Reference ADODB script
Sub OnClick(Byval Item)
Dim sPath, sFile, conn, rs
Dim objTag
sPath = HMIRuntime.Tags("CsvFolder").Read ' e.g. D:\Project\CSV
sFile = "Tags.csv"
Set conn = CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sPath & ";" & _
"Extended Properties="text;HDR=YES;FMT=Delimited(;);";"
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT TagName, TagValue FROM Tags.csv", conn, 3, 1
Do Until rs.EOF
Set objTag = HMIRuntime.Tags(rs.Fields("TagName").Value)
objTag.Value = CDbl(rs.Fields("TagValue").Value)
objTag.Write
rs.MoveNext
Loop
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
End Sub
5.3 Notes on the provider
- On a 32-bit WinCC Runtime (the default for V13-V17 PC RT), the 32-bit ACE provider
Microsoft.ACE.OLEDB.12.0must be installed. The 64-bit provider cannot be loaded into a 32-bit process. - On a 64-bit WinCC Unified Runtime, install the matching 64-bit ACE provider.
- The legacy
Microsoft.Jet.OLEDB.4.0provider is 32-bit only and is no longer shipped with current Windows builds; avoid it for new projects. - The Extended Properties string is case-sensitive on some driver versions. Use
text;HDR=YES;FMT=Delimited(;);exactly as shown.
6. Reading the HMIRuntime.Trace Output
Trace output is essential for debugging a CSV reader. There are three reliable ways to see HMIRuntime.Trace messages in WinCC RT Advanced V13 SP1+:
- Global Script Diagnostics window (RT Professional only): add an Application Window of type Global Script / GSC-Diagnose to a WinCC picture. This option is not available on RT Advanced panels.
-
apdiag.exe - Output Window: launch
apdiag.exefrom the WinCC installation, then choose Output Window > Open. The default install path on a V13 SP1 PC station isC:\Program Files (x86)\Siemens\Automation\SCADA-RT_V11\WinCC\uTools\apdiag.exe; on V17 it isC:\Program Files\Siemens\Automation\WinCC RT Advanced\uTools\apdiag.exe. -
apdiag.exe - OnFile: in the same tool, choose Diagnostics > OnFile and enable printf to file. Trace messages are written to rolling text files named
onprintfX.txtinC:\Program Files (x86)\Siemens\WinCC\diagnose\(or the equivalent path on a newer installation).
onprintfX.txt on a service laptop. There is no on-screen diagnostics window on the panel itself.
7. WinCC Unified - Native CSV Export of Runtime Data
If the goal is not to read a CSV into WinCC but to write WinCC Runtime data out to a CSV (for analytics, MES handover, or post-processing), TIA Portal V17 introduced a native control in the Unified UI, refined further in V19, V20, and V21. The official Siemens documentation describes the workflow as follows:
- Add a control from the My controls toolbar category onto a Unified screen.
- Bind the control to the HMI tag(s) whose values should be exported.
- Use the Export to CSV action on the toolbar of the control at Runtime to save the current values of the bound tag to a CSV file on the local file system.
- The exported file uses the standard Unicode CSV encoding and respects the configured column order from the control's tag binding.
For the full step list, screenshots, and the supported tag types, see the Siemens TIA Portal Help for WinCC Unified: Further processing RT data via CSV (RT Unified) - WinCC Unified. The same article exists in the V17, V18, V19, and V20 documentation sets under the equivalent menu path.
8. Tag Type Handling and Locale Pitfalls
The most common runtime failure on a CSV import script is a type mismatch. Tag the column types in your CSV ahead of time and match them to the HMI tag data type.
| HMI Tag Type | FSO Conversion | Example Source String | Notes |
|---|---|---|---|
| Int / DInt |
CLng(arrItems(1)) or CInt(...)
|
1234 |
Watch for signed range on DInt (-2,147,483,648 .. 2,147,483,647) |
| Real / LReal | CDbl(arrItems(1)) |
3.14 or 3,14 depending on locale |
Use Replace(strValue, ".", ",") to force German locale parsing |
| Bool | CBool(arrItems(1) = "1") |
0 / 1
|
HMI Bool tags accept 0 and 1; True / False literals are safer |
| String (WString) | CStr(arrItems(1)) |
any text | For multi-word values, ensure the CSV uses quotes |
| DateTime | CDate(arrItems(1)) |
2025-11-15 14:32:00 |
Locale-sensitive; ISO 8601 strings are the safest input |
, as the decimal separator, while a CSV exported by an English-locale system uses .. If the value is 3,14, CDbl("3.14") on a German system produces 314 (the dot is read as a thousands separator), which silently corrupts the imported value. Force the format with Replace() before conversion, or set the script culture with SetLocale.
9. Error Handling Pattern
Wrap each block that touches the file system or the tag database with On Error Resume Next + Err.Number checks. The reference block below covers the four most common failures (file missing, file locked, tag not found, type mismatch):
Sub OnClick(Byval Item)
On Error Resume Next
Dim fso, objFile, strLine, arrItems
Dim strFilename, tagName, tagValue, objTag
Set fso = CreateObject("Scripting.FileSystemObject")
strFilename = HMIRuntime.Tags("Filename").Read
If Err.Number <> 0 Then
HMIRuntime.Trace "ERR read Filename tag: " & Err.Description & vbCrLf
Exit Sub
End If
If Not fso.FileExists(strFilename) Then
HMIRuntime.Trace "File not found: " & strFilename & vbCrLf
Exit Sub
End If
Set objFile = fso.OpenTextFile(strFilename, 1)
If Err.Number <> 0 Then
HMIRuntime.Trace "ERR opening file (locked?): " & Err.Description & vbCrLf
Exit Sub
End If
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If Len(strLine) > 0 Then
arrItems = Split(strLine, ";", -1, 1)
If UBound(arrItems) >= 1 Then
tagName = CStr(arrItems(0))
tagValue = CDbl(arrItems(1))
Set objTag = HMIRuntime.Tags(tagName)
If Err.Number = 0 Then
objTag.Value = tagValue
objTag.Write
Else
HMIRuntime.Trace "ERR tag " & tagName & ": " & Err.Description & vbCrLf
Err.Clear
End If
End If
End If
Loop
objFile.Close
End Sub
10. Performance and File I/O Best Practices
-
Avoid polling. Do not put a tight
Do ... Loopwith a fixed sleep in a cyclic script. Trigger the import on a button click, on a value change of a tag, or with a once-per-minute scheduler tag driven by the PLC. -
Cache the FSO. Create the
FileSystemObjectonce per Sub and set it toNothingat the end. Re-creating it on every call adds ~5-20 ms of overhead. -
Limit the file size. FSO ReadLine on a 50,000-line CSV will block the VBScript thread for seconds and freeze the screen. For large imports, use the ADODB method with a
SELECT TOP Nclause. -
Disable screen updates during bulk writes. On RT Professional, call
HMIRuntime.Screens.Item("Main").ScreenItems(...).Visible = Falseon heavy-import tags whose faceplates would otherwise repaint per value change. -
Validate before write. Add a small whitelist check (
If tagName = "Recipe.MaxPressure" Then ...) to prevent an attacker who can write to the CSV from injecting arbitrary tag names.
11. Step-by-Step Implementation (Tia Portal V17 example)
- In the TIA Portal project, open the HMI device (PC station with RT Professional or RT Advanced).
- In the project tree, expand HMI tags and add an internal String tag named
Filename. Add a second internal tagCsvFolderif you are using the ADODB method. - Add the destination tags (e.g.
Recipe.SetpointPressure,Recipe.SetpointFlow) and ensure their data type matches the CSV columns. - Open a screen, add a button, and configure the Click event to call a VBScript action.
- Paste the FSO reference script (section 4.1) or the ADODB reference script (section 5.2) into the action editor.
- Compile and download the project to the PC station.
- Start WinCC Runtime. Click the button. The script reads the configured CSV and writes the values to the HMI tags, which are then available to the connected S7-1200 via area pointers or to faceplates via tag bindings.
- For verification, open
apdiag.exeas described in section 6 and confirm the trace lines appear in order.
12. Verification Procedure
- File reachability: confirm the Filename tag holds a valid path. A typo silently falls into the Else branch and the only symptom is "File not found" in the trace.
-
Tag existence: check that every
tagNamein the CSV exists in the project tag table. An unknown tag raisesErr.Number 0x8004271A(tag not found). -
Type match: confirm each value converts cleanly. Add a try/catch with
CDblwrapped inOn Error Resume Nextto catch type mismatches. -
Trace log: confirm the trace output shows one
<tag> Value: <value>line per imported row. - PLC feedback: if the imported tag is connected to the S7-1200 (e.g. via a connection in Connections), watch the corresponding DB on the PLC in TIA Portal's Monitor & Force to confirm the value reached the controller.
- HMI display: bind an I/O field to the imported tag and confirm the value updates on screen after the button click.
13. Troubleshooting Matrix
| Symptom | Likely Cause | Fix |
|---|---|---|
| File not found in trace | Wrong path, UNC permission, or relative path resolved from a different working directory | Use an absolute path, verify with FileExists, and run the WinCC Runtime service as a user with read rights |
| Tag value stays at 0 | CDbl produced 0 because of a locale decimal-separator mismatch | Replace . with , (or vice versa) before CDbl |
| Object variable not set (Error 91) |
HMIRuntime.Tags("Name") returned Nothing for an unknown tag |
Validate tag names against the project tag table |
| Type mismatch (Error 13) | Empty cell, BOM character, or string in a numeric column | Wrap conversion in If IsNumeric(...) Then
|
| File is locked by another process | Excel or the MES tool still has the CSV open for write | Open with OpenTextFile(path, 1, True) (third argument = create if missing) only if writing, not reading; otherwise copy the file first |
| ADODB "Cannot find installable ISAM" | Wrong Extended Properties string or missing ACE provider | Install the matching bitness ACE provider and verify the connection string with a small VBS test |
| Trace messages invisible on a Comfort Panel | RT Advanced panel has no on-screen diagnostics window | Use the apdiag OnFile path to a USB stick |
14. FAQ
Can WinCC Runtime Advanced on a Comfort Panel read a CSV?
Yes. The VBScript host on a Comfort Panel supports the same FSO and ADODB COM objects as a PC-based Runtime. The only difference is diagnostics: there is no on-screen trace window, so use apdiag.exe with OnFile to dump trace messages to a USB stick.
Why does my imported Real value show as 314 instead of 3.14?
Locale decimal-separator mismatch. A German Windows reads 3.14 as three-hundred-fourteen because the dot is the thousands separator. Call Replace(strValue, ".", ",") before CDbl, or set the script culture with SetLocale "en-US".
Should I use FSO or ADODB for a 100-row CSV?
FSO. For under ~5,000 rows with a stable delimiter, FSO is faster to set up, has no driver dependency, and has zero installation footprint. Switch to ADODB only when you need SQL-style filtering, header-driven column binding, or RFC 4180 quoted-field handling.
Where does HMIRuntime.Trace output appear in WinCC RT Advanced V13 SP1?
On a PC station, open C:\Program Files (x86)\Siemens\Automation\SCADA-RT_V11\WinCC\uTools\apdiag.exe and use the Output Window. For unattended logging, enable OnFile to write onprintfX.txt into the WinCC\diagnose folder.
How do I export WinCC Runtime data to CSV in TIA Portal V17/V21 Unified?
Use the My controls toolbar item in WinCC Unified, bind it to the source tags, and trigger the Export to CSV action at runtime. The official step-by-step is documented at Further processing RT data via CSV (RT Unified) - WinCC Unified.