Reading WinCC Flexible I/O Field Values in VBScript for Filenames

David Krause13 min read
SiemensTutorial / How-toWinCC
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 Flexible 2008 (and its successor, WinCC Comfort/Advanced inside TIA Portal) lets an engineer drive HMI behavior through VBScript attached to events on screens, buttons, value changes, and schedulers. A recurring task in this environment is reading the value the operator has just typed into an I/O Field and using it as the file name of a log, recipe export, alarm archive, or PDF report. The mechanism is identical whether the runtime is a SIMATIC Comfort Panel, a SIMATIC Basic Panel with scripting support, or a PC-based WinCC Runtime.

The runtime object model exposes the HMI tag behind the I/O Field through the SmartTags() function. Combining that value with a directory string and the Scripting.FileSystemObject COM object gives a complete, self-contained "operator-typed filename" workflow that does not require a custom DLL, an OPC bridge, or a separate archive application.

This reference covers the WinCC Flexible path end to end and provides the equivalent VBScript for the modern WinCC Unified V20 I/O Field object, because most field panels that shipped with WinCC Flexible 2008 SP5 are now being migrated to TIA Portal projects.

Generational note. WinCC Flexible 2008 SP5 was the last release of the WinCC Flexible product line. The SmartTags() syntax described below is identical in WinCC Comfort and WinCC Advanced inside TIA Portal V13 SP1 through V18. WinCC Unified (TIA Portal V16 and later, currently V20) replaces SmartTags() with HMIRuntime.Tags(...).Read() / .Write().

Prerequisites

Before the script can read a tag value and write a file, confirm the following prerequisites are met on both the engineering station and the runtime target.

  • Engineering software. WinCC Flexible 2008 SP5 (legacy line) or TIA Portal V13 SP1 / V14 / V15 / V15.1 / V16 / V17 / V18 with WinCC Comfort or WinCC Advanced installed.
  • Runtime target. A SIMATIC panel that supports VBScript: TP/OP/MP 277, TP/OP/MP 377, all Comfort Panels (TP700–TP2200, KP/KT), WinCC Runtime Advanced on a PC, or the modern Unified Comfort Panels (MTP/MTP Unified) for the WinCC Unified path.
  • Project structure. At least one HMI tag, one screen, and one I/O Field configured on that screen.
  • File system rights. For PC Runtime, write access to the chosen path (e.g. C:\Logs\, a USB stick mounted as \USB\ on a panel, or an SD card path). Panel runtimes write to the project path, the storage card path, or a USB stick plugged into the front USB.
  • VBScript support enabled. In WinCC Flexible, VBScript is enabled per project by default on the panels listed above; legacy Basic Panels (KTP400 Basic mono) and the Micro Panel OP 73 / TP 177A do not support VBScript.

How the I/O Field Connects to a Tag

The I/O Field screen object is purely a view on a tag. It does not store its own data. When the operator types into the field, the runtime writes the value into the bound HMI tag; when a script reads the tag, it reads the same value the operator sees. The complete data path is therefore:

  1. Engineer configures an HMI tag (e.g. Tag_string) of type String or WString.
  2. Engineer drops an I/O Field on a screen and binds the Process / Variable property to Tag_string.
  3. Runtime displays the current tag value inside the I/O Field.
  4. Operator types a new value; runtime pushes the text into Tag_string.
  5. Script reads Tag_string and uses it as a filename component.

Tag Configuration for Filename Use

Because the value is going to be part of a file path, the tag type and length must be chosen carefully. The table below summarises the settings that work in practice.

Property Recommended value Why
Name e.g. Tag_string Script address — must match the SmartTags argument.
Data type WString (preferred) or String WString supports Unicode and the full ASCII path set; String is sufficient for Latin-1 filenames.
Length 50 – 200 characters Allow room for separators and extensions without truncating.
Acquisition cycle 100 ms (or "On demand") Operator types, runtime writes; no cyclic update is required.
PLC connection None (internal tag) Filenames do not need to go to the PLC.
Initial value Empty or a sensible default such as Log Prevents an empty file name when the operator never types.
Persistent in Runtime Optional Keep last typed name across restart if desired.
File-system reserved characters. < > : " / \ | ? * are illegal in Windows file names. If the operator is allowed to type arbitrary text, sanitise the value (see Sanitising the Filename below) before passing it to FileSystemObject.

Binding the Tag to the I/O Field

  1. In the project tree, open the screen and drop an I/O Field from the toolbox.
  2. In the Properties > General dialog, set Mode to Input/Output (or Output if the script will set the value).
  3. Click the Process / Variable property and select Tag_string from the tag browser.
  4. Set Display type to String (not Decimal, Binary, etc.).
  5. Set Length of the displayable value to match the tag length (e.g. 50).
  6. Optionally, configure a Limit text in the Appearance tab and assign an Input finished event (used in the next step).

WinCC Flexible VBScript Object Model — SmartTags()

In WinCC Flexible, WinCC Comfort, and WinCC Advanced, the global SmartTags collection is the primary way to read or write a tag from VBScript. The collection behaves like a dictionary keyed by tag name and returns a variant containing the current value.

Dim v
v = SmartTags("Tag_string")  ' Read
SmartTags("Tag_string") = "NewValue"  ' Write

Key behaviours of SmartTags:

  • It is implicitly available in every VBScript action — no Option Explicit declaration is required, and no CreateObject call is needed.
  • The argument is a string literal matching the HMI tag name. Multilingual projects with a single tag across languages still use the engineering tag name.
  • Reads are taken at script execution time, not at script edit time, so a subsequent SmartTags("Tag_string") access in the same script returns the live value.
  • Writes are queued through the same runtime data manager used by the I/O Field, so the value updates in the screen as soon as the script returns.

Reading the I/O Field Value

Place the following VBScript on the Input finished event of the I/O Field, or on the Click event of a button next to the field. Both events fire after the runtime has accepted the operator input and committed it to the tag.

' --- WinCC Flexible / Comfort / Advanced VBScript ---
' Event: I/O Field "Tag_string" -> Input finished
' Purpose: read the typed value, compose a filename, and write a file.

Dim strBaseName
Dim strFullPath
Dim fso, ts

' 1. Read the value the operator just typed.
strBaseName = SmartTags("Tag_string")

' 2. Guard against an empty / null value.
If Len(strBaseName) = 0 Then
    SmartTags("Tag_string") = "Log"
    strBaseName = "Log"
End If

' 3. Compose the full path.
strFullPath = "C:\Logs\" & strBaseName & ".csv"

' 4. Create the file and write content.
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts  = fso.CreateTextFile(strFullPath, True, True)   ' overwrite, Unicode
ts.WriteLine "Timestamp,Value"
ts.WriteLine Now() & ",0"
ts.Close

Set ts  = Nothing
Set fso = Nothing

The same script on a panel runtime must use a writable storage path. The conventional locations are:

  • External storage card: \Storage Card\Logs\
  • USB stick (Comfort Panels and Unified Panels): \USB\Logs\
  • Network share (PC Runtime, RT Advanced): \\SERVER\Share\Logs\

Composing the Filename

The SmartTags value can be concatenated with fixed text, the current date, or other tags to form the final path. The most common patterns are shown below.

Pattern VBScript Sample output
Operator text + extension "C:\Logs\" & SmartTags("Tag_string") & ".csv" C:\Logs\MyFile.csv
Operator text + timestamp "C:\Logs\" & SmartTags("Tag_string") & "_" & Year(Now) & Right("0" & Month(Now),2) & Right("0" & Day(Now),2) & ".csv" C:\Logs\MyFile_20260214.csv
Operator text + counter tag "C:\Logs\" & SmartTags("Tag_string") & "_" & CStr(SmartTags("Tag_counter")) & ".csv" C:\Logs\MyFile_0042.csv
Subfolder per day "C:\Logs\" & Year(Now) & "-" & Right("0" & Month(Now),2) & "\" & SmartTags("Tag_string") & ".csv" C:\Logs\2026-02\MyFile.csv

Sanitising the Filename

The most common runtime error when feeding a tag value to FileSystemObject is the operator typing a reserved character. A small helper function strips and replaces them:

Function SafeFileName(ByVal s)
    Dim i, ch, out
    Dim bad
    bad = Array("<", ">", ":", """", "/", "\\", "|", "?", "*")
    out = ""
    For i = 1 To Len(s)
        ch = Mid(s, i, 1)
        If InStr("<>:"/\|?*", ch) > 0 Then
            out = out & "_"
        ElseIf ch = Chr(32) Then
            out = out & "_"
        Else
            out = out & ch
        End If
    Next
    ' Trim trailing dot or space (Windows rule).
    Do While Right(out, 1) = "." Or Right(out, 1) = " "
        out = Left(out, Len(out) - 1)
    Loop
    If Len(out) = 0 Then out = "Log"
    SafeFileName = out
End Function

Use it before concatenating:

strFullPath = "C:\Logs\" & SafeFileName(SmartTags("Tag_string")) & ".csv"

File System Operations with FileSystemObject

WinCC Flexible VBScript supports the standard Scripting library shipped with Windows. The two methods most often used together with an I/O Field value are:

Method Use Notes
fso.CreateTextFile(path, overwrite, unicode) Create a new log/report file Set overwrite = True to replace; unicode = True for non-ASCII operator input.
fso.OpenTextFile(path, mode) Append to an existing log Mode 1 = read, 2 = write/overwrite, 8 = append.
fso.FolderExists(path) Check the target folder Create it on the fly with CreateFolder.
fso.FileExists(path) Check before overwriting Combine with a confirm dialog on the screen.
fso.DeleteFile(path) Remove old logs Use cautiously from a button event.
' Ensure the target folder exists before writing.
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists("C:\Logs") Then
    fso.CreateFolder "C:\Logs"
End If

Complete Working Sample — Panel Runtime

The script below is bound to the Click event of a Save log button on a Comfort Panel screen. The I/O Field "FileNameIO" is bound to tag Tag_string.

' Event: Button "SaveLog" -> Click
' Panel: TP900 Comfort, WinCC Comfort V16
' Writes: \Storage Card\Logs\<operator_text>_<yyyymmdd>.csv

Dim fso, ts
Dim raw, safe, folder, full

raw  = SmartTags("Tag_string")
safe = SafeFileName(raw)

folder = "\Storage Card\Logs\"
full   = folder & safe & "_" & _
         Year(Now) & Right("0" & Month(Now),2) & Right("0" & Day(Now),2) & ".csv"

Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(folder) Then fso.CreateFolder folder

Set ts = fso.CreateTextFile(full, True, True)
ts.WriteLine "Tag,Value,Unit"
ts.WriteLine "Pressure," & CStr(SmartTags("Tag_pressure")) & ",bar"
ts.WriteLine "Flow,"     & CStr(SmartTags("Tag_flow"))     & ",l/min"
ts.Close

Set ts  = Nothing
Set fso = Nothing

' Show feedback in an I/O Field bound to Tag_status.
SmartTags("Tag_status") = "Saved: " & full

WinCC Unified V20 Equivalent

In WinCC Unified (TIA Portal V16 and later, currently V20), the SmartTags global is gone. Tags are read and written through the HMIRuntime object. The rest of the logic (String tag, I/O Field, FileSystemObject) is unchanged. The IO field (RT Unified) object behaves identically to the WinCC Flexible I/O Field: it shows the configured value in the chosen output format and, in input mode, writes operator text back to the bound tag.

' --- WinCC Unified V20 VBScript ---
' Event: Button "SaveLog" -> Click
' Bound tag: Tag_string (WString)

Dim fso, ts
Dim raw, safe, folder, full

raw  = HMIRuntime.Tags("Tag_string").Read()
safe = SafeFileName(CStr(raw))

folder = "\Storage Card\Logs\"
full   = folder & safe & "_" & _
         Year(Now) & Right("0" & Month(Now),2) & Right("0" & Day(Now),2) & ".csv"

Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(folder) Then fso.CreateFolder folder

Set ts = fso.CreateTextFile(full, True, True)
ts.WriteLine "Tag,Value,Unit"
ts.WriteLine "Pressure," & CStr(HMIRuntime.Tags("Tag_pressure").Read()) & ",bar"
ts.Close

Set ts  = Nothing
Set fso = Nothing

HMIRuntime.Tags("Tag_status").Write "Saved: " & full
Unified V20 specifics. HMIRuntime.Tags(name).Read() and .Write(value) are synchronous by default. For asynchronous behaviour (e.g. to avoid blocking the UI on a slow write), append a quality/timestamp argument: HMIRuntime.Tags("Tag_string").Read(1). The SmartTags alias is not available in Unified, so any project migrated from WinCC Flexible must be searched for SmartTags and rewritten with the new pattern.

Verification

After configuring the tag, the I/O Field, and the script, verify the chain in the order below.

  1. Tag test. Open the tag table, monitor Tag_string, and confirm it updates as the operator types.
  2. Script test (simulator). In the WinCC Flexible / Comfort / Advanced ES, run the project with the simulator. Click the button bound to the script and check the configured log path for a file with the typed name.
  3. File system check. On the panel, open the file manager (where available) or, on a PC runtime, open Explorer at the target path and confirm the file exists with the expected size and encoding.
  4. Empty-value check. Clear the I/O Field, press the button, and confirm the script falls back to a default name rather than raising an error.
  5. Reserved-character check. Type a value such as Log/2026 and verify that the sanitiser replaces the slash.
  6. Unified V20 path check. Repeat steps 1–5 against a Unified Panel or Unified PC Runtime if the project is being migrated.

Common Errors and Troubleshooting Matrix

Symptom Likely cause Resolution
Script runtime error 13 — Type mismatch Tag is a numeric type but the script treats it as a string Change the tag data type to WString or wrap with CStr().
Script runtime error 70 — Permission denied Panel path C:\Logs\ is read-only on the runtime Use \Storage Card\Logs\ or \USB\Logs\; confirm write access on PC Runtime.
Script runtime error 76 — Path not found Subfolder does not exist Call fso.CreateFolder after a FolderExists check.
Empty file written Operator cleared the I/O Field Set a default value in the If Len(...)=0 branch.
Filename contains the I/O Field tag name, not its value Script reads the tag name literal by mistake Confirm the argument to SmartTags is a quoted string and matches the engineering tag name exactly.
File name shows ?? for non-ASCII File opened in ASCII mode Open with the third argument True for Unicode: fso.CreateTextFile(path, True, True).
Unified: Object doesn't support this property or method Script still uses SmartTags Replace with HMIRuntime.Tags("name").Read() / .Write().
Unified: tag returns 0 instead of text Tag is a 32-bit integer, not a string Re-create the HMI tag as WString and re-bind the I/O Field.

Best Practices

  • Sanitise before concatenating. Apply SafeFileName to every value coming from the operator; never trust screen input.
  • Default value at runtime. Provide a sensible default (e.g. Log, Recipe01) so the script does not fail when the I/O Field is empty.
  • Folder existence check. Wrap CreateTextFile with a FolderExists / CreateFolder pair to handle first-run and SD-card-swap cases on panels.
  • Unicode mode. Open files in Unicode (CreateTextFile(path, overwrite, True)) to support German, French, Spanish, Chinese, and Cyrillic operator input.
  • Path constants in one place. Define a single VBScript constant for the log folder and reuse it; the storage path differs between PC Runtime, panel runtime, and Unified panels.
  • Status feedback tag. After saving, write the full path to a status I/O Field so the operator sees a confirmation on the same screen.
  • Migration readiness. When porting a WinCC Flexible project to TIA Portal V16+ Unified, search and replace SmartTags( with the HMIRuntime.Tags(...).Read() / .Write() pattern; the I/O Field configuration and the FileSystemObject logic stay the same.
  • Test on the real target. The simulator does not enforce panel write permissions; always validate on the actual device with the actual storage card or USB stick.

FAQ

Why does my VBScript read the I/O Field tag name instead of its value?

The SmartTags("Tag_string") argument must be a quoted string literal that matches the engineering tag name, not a variable that holds the tag name. In WinCC Unified V20 use HMIRuntime.Tags("Tag_string").Read(); the equivalent of passing a variable for the name is HMIRuntime.Tags(varName).Read() where varName is a string variable.

Which tag data type should I use for a filename I/O Field?

Use WString with a length of 50–200 characters. String is sufficient for Latin-1 text; WString is required for Unicode operator input and is the default in WinCC Unified V20.

Can I read the I/O Field value from a WinCC Unified V20 faceplate script?

Yes. Inside a faceplate, the tag interface property is the local equivalent of the I/O Field binding. Read it with HMIRuntime.Tags("InterfaceProperty").Read() on the faceplate container, then apply the same FileSystemObject pattern shown above.

How do I prevent the operator from typing illegal Windows characters?

Run the typed value through a sanitiser that replaces < > : " / \ | ? * and spaces with underscore, then trims trailing dots and spaces, and finally substitutes a default if the result is empty. Call this helper before concatenating the path.

Why is the file written as ASCII on the panel and shows ? for non-English characters?

You opened the file with the third argument of CreateTextFile set to False. Open it as Unicode: fso.CreateTextFile(fullPath, True, True). Comfort Panels and Unified Panels default to a Unicode-aware file system, so the True flag is safe on every runtime.

Back to blog