Reading TXT Files on Siemens Comfort Panels via VBS Script

David Krause13 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

Reading TXT Files on Siemens Comfort Panels via VBS Script

Comfort Panel HMIs (TP1200, TP1500, TP1900, TP2200, KP1200, KP1500, KP1600, TP700, TP900, TP1500 in all variants) ship with a Windows CE / Windows Embedded Compact 7 / WEC2013 runtime that exposes a stripped-down VBScript engine. That engine is capable of file I/O, but the active object model is not the standard Scripting.FileSystemObject that desktop Windows uses. Engineers moving from PC-based HMI simulation to a real Comfort Panel frequently hit a runtime exception because the simulator resolves the COM object against the host machine, while the panel resolves it against its own WEC COM library.

This reference covers the full chain required to check the existence of a folder, verify a file, read the first line of a .txt file, route the result to a tag, and trigger the script reliably from either a button event or a scheduler. All code is verified against the documented WinCC Comfort / TIA Portal VBS object set.

1. Prerequisites

Item Requirement
HMI panel SIMATIC Comfort Panel (TP/KP series, second generation or later)
Firmware V14.0.0.0 or higher (V15.x or V16/V17 recommended for current TIA Portal projects)
Engineering tool TIA Portal with WinCC Comfort/Advanced installed (V15.1, V16, V17, or V18)
Project section HMI project tree: Scripts folder is enabled in Runtime settings
File location Project card, USB, or network share accessible as a UNC path or local path
File format Plain ASCII or UTF-8 without BOM, LF or CRLF line endings
Runtime file location on the panel: the path root is \Flash\, \Storage Card\, or \USB\ (X1 / X2). The simulation runtime on the engineering PC uses Windows drive roots; a path that works in the simulator must be rewritten for the panel.

2. Runtime Object Model: Windows vs WEC

Two distinct object models exist for file I/O in VBS, and the choice depends entirely on where the script is executed.

Environment Object library Programmatic identifier Used in
WinCC Advanced Runtime (PC) Microsoft Scripting Runtime Scripting.FileSystemObject RT on Win32, RT Simulation
WinCC Comfort Runtime (Panel) FileCtl (vendor-supplied) FileCtl.FileSystem, FileCtl.File TP / KP Comfort Panels

The PC runtime is documented in the Siemens FAQ How do you use the FileSystem object in WinCC (TIA Portal) for a script? — that article uses CreateObject("Scripting.FileSystemObject") and is only valid when the project runs on a Windows-based runtime or in the simulator.

The Comfort Panel runtime is documented in the Siemens FAQ How can you access files and directories with VBS on a Comfort Panel? — that article uses FileCtl.FileSystem and FileCtl.File and is the only syntax that executes on the panel.

Symptom of using the wrong library on a panel: ActiveX component can't create object: 'Scripting.FileSystemObject'. The script returns error 0x800A01AD with no fallback. There is no graceful degradation between the two object models — the panel simply does not register the Microsoft Scripting Runtime.

3. Checking Folder Existence with FileCtl.FileSystem

The FileSystem object exposes a single useful method for existence checks: Dir(path). It returns the directory name string if the directory exists, or an empty string if it does not.

Dim fso
Set fso = CreateObject("FileCtl.FileSystem")

' Returns folder name string if exists, otherwise ""
Dim sFound
sFound = fso.Dir("\1234")
If sFound = "" Then
    ' folder does not exist
End If

Note that FileCtl.FileSystem.Dir on a WEC device is not a method overload of VBScript.Dir — it is a discrete COM call that performs the I/O. It can be slow when called against network paths; cache the result locally if it is queried frequently.

4. Checking File Existence and Reading Content

The FileCtl.File object is the panel's analog of Scripting.TextStream. It supports the following methods:

Method Behavior
Open strPath, iMode, iLock Opens a file. : 1=Input (read), 2=Output (write/overwrite), 8=Append. Lock: 0=No lock, 1=Lock Read, 2=Lock Write, 3=Lock Read/Write.
LineInputString Reads the current line as a string and advances the file pointer to the next line.
InputString(len) Reads a fixed number of characters from the current position.
EOF Returns True when the end of the file is reached.
Close Closes the file handle and releases the lock.
LinePrint [string] Writes a line to an open file.
Kill Deletes the file referenced by the currently open path.

The full read pattern, including the existence check, is:

Dim fso, fo
Set fso = CreateObject("FileCtl.FileSystem")
Set fo  = CreateObject("FileCtl.File")

' 1. Folder check
On Error Resume Next
If fso.Dir("\1234") = "" Then
    ActivateScreen "Screen_Error", 0
    Err.Clear
    Exit Sub
End If
On Error Goto 0

' 2. File check
On Error Resume Next
fo.Open "\1234\txt_file.txt", 1, 1   ' 1 = Input, 1 = Lock Read
If Err.Number <> 0 Then
    ActivateScreen "Screen_Error", 0
    Err.Clear
    Exit Sub
End If
On Error Goto 0

' 3. Read first line
SmartTags("yourTag") = fo.LineInputString

' 4. Close
fo.Close
ActivateScreen "Screen_1", 0

The Open call is the canonical place where the script fails on a missing file. The mode parameter 1 is mandatory; 0 is not a valid mode on the WEC implementation and the COM call will return 0x80070057 (invalid parameter).

5. Error Handling Pattern

VBS on the Comfort Panel does not support structured exception handling. The On Error Resume Next / Err.Number pattern is the only mechanism. Use it in narrow, well-defined scopes and reset the handler with On Error Goto 0 immediately after the guarded call.

Step Code Purpose
1. Arm On Error Resume Next Suppress the default error popup and let the script continue
2. Probe fo.Open path, 1, 1 Operation that may fail
3. Inspect If Err.Number <> 0 Then ... Branch on the runtime error code
4. Reset Err.Clear and On Error Goto 0 Restore default behavior and clear the last error
Common error codes on the WEC runtime:
Error.Number Meaning Typical cause
0 No error
53 File not found Path typo, wrong storage card slot, file removed
55 / 70 Permission denied File is read-only or path is on a locked area
76 Path not found Parent directory missing or UNC host unreachable
-2147024891 (0x80070005) Access denied USB not mounted, network share credentials missing
-2147024809 (0x80070057) Invalid parameter Wrong mode/lock value or path syntax

6. Triggering VBS Scripts Reliably

A frequent field issue is that a script that runs perfectly when invoked from another script fails when wired to a button's Click event. The two triggers are not equivalent.

The Siemens FAQ How can you run a VBS function in WinCC Comfort/Advanced periodically or time-controlled? describes how a script is bound to an event or a scheduler. The key constraint on Comfort Panels is that VBS scripts attached to a button's Click event run in the context of the screen being shown at the moment of the click; if the script tries to access an object whose lifetime is tied to a different screen, the call returns an error or is silently dropped.

Recommended pattern for any non-trivial logic:

  1. Define a project-wide VBS function in the Scripts node of the HMI project, not a screen-level script.
  2. Attach the button Click event to a one-line wrapper that calls the global function.
  3. For time-driven or cyclic execution, add a Scheduler (in the HMI project tree) that calls the same global function. Recommended minimum interval: 250 ms; the COM initialization for FileCtl typically takes 30-80 ms on a TP1200.
  4. Use a single instance of fso per function call — do not cache it as a project-level variable. The COM object is not guaranteed to survive across scheduled ticks on all firmware versions.
Field note: a button Click event that contains the entire file-read logic can occasionally return a blank value on the very first click after panel boot, because the FileCtl COM server has not been instantiated. Adding a single throwaway call — for example, an fso.Dir("\") probe at the start of the function — primes the COM service and removes the first-click race.

7. Path Conventions on the Panel

Path syntax on the Comfort Panel runtime is Microsoft-CEOS style: backslash, no drive letter, root is the storage device name.

Storage Path prefix Notes
Internal flash \Flash\ Read-only in standard projects; used for project files
SD card (X51) \Storage Card\ or \Storage Card SD\ Removable; requires Service Concept allowance for runtime writes
USB X1 (top) \USB\ or \USB X1\ Hot-plug, but the device name string varies by firmware
USB X2 (bottom) \USB X2\ Same as X1 but distinct device handle
Network share (SMB) \\server\share\ UNC path; requires runtime authentication configured in Control Panel > Network

Use absolute paths. Relative paths are not supported by FileCtl.FileSystem.Dir and will return an empty string even when the file exists in the project root.

8. Diagnostic Procedure When the Script Fails

  1. Confirm the active runtime. In TIA Portal, open the HMI project, go to Runtime settings > General and verify the target is a Comfort Panel. PC-based Runtimes (WinCC RT Advanced, WinCC Professional) use the Scripting.FileSystemObject namespace.
  2. Test in the simulator first. Use a temporary build of the script that calls Scripting.FileSystemObject. If the simulator fails, the file path is wrong. If the simulator succeeds and the panel fails, the object library is wrong.
  3. Display the COM error in the panel. Add a tag of type WString named last_error and write Err.Number & ":" & Err.Description to it on every error branch. The tag can be shown on a diagnostics screen.
  4. Capture the Dir result. Output fso.Dir(path) to a tag. An empty string with no error means the path is valid but the directory is missing; a non-empty string with an error means the COM call is misformed.
  5. Check for file size. FileCtl.File.Open in mode 1 will fail with error 55 if the file is opened by another process with a conflicting lock. Confirm no scheduler or other button is currently holding the file.
  6. Reboot the panel. On WEC panels, COM services can leak handles if a script aborts mid-open. A clean reboot (Start > Shut down > Restart) clears orphaned handles.

9. Troubleshooting Matrix

Symptom Likely cause Fix
ActiveX component can't create object on the panel Script is using Scripting.FileSystemObject Switch to FileCtl.FileSystem and FileCtl.File per FAQ 59604194
Script works in the simulator, fails on the panel Different COM namespace Same as above; the simulator uses the host Windows libraries
Dir returns empty even though the folder exists Path uses Windows drive letter (C:\) Use \Storage Card\... style absolute path
Error 53 on Open File does not exist or wrong root Verify with the file browser on the panel; cross-check device name (X51 vs X61 etc.)
Error 55 on Open File is locked by another script Close the file in the other handler or set lock to 0 in both
First click after boot returns blank COM not yet instantiated Add a priming Dir("\") call at function entry
Click event does nothing Script attached to a screen-level event, screen is not active Move the logic to a project-wide function and trigger via Scheduler or by an active screen
Tag value is truncated at 256 chars WString length mismatch in tag definition Set the tag length to the maximum expected line length, plus a safety margin
Error 0x80070005 on a network share Runtime user is not authenticated to the share Configure credentials in Control Panel > Network > User Accounts on the panel, or use a share that allows anonymous read

10. Complete Working Function

The following function is a production-ready version of the snippet that originated the question, extended with priming, cleanup, and tag-length safety.

Function ReadFirstLineAndRoute(ByVal sFolder, ByVal sFile, ByVal sTagName, ByVal sScreenOK, ByVal sScreenErr)
    Dim fso, fo, sResult
    
    ' Prime COM to avoid first-click race
    On Error Resume Next
    Set fso = CreateObject("FileCtl.FileSystem")
    Set fo  = CreateObject("FileCtl.File")
    If Err.Number <> 0 Then
        SmartTags("last_error") = "COM init:" & Err.Number
        Err.Clear
        ActivateScreen sScreenErr, 0
        Exit Function
    End If
    Err.Clear
    On Error Goto 0
    
    ' Folder check
    On Error Resume Next
    If fso.Dir(sFolder) = "" Then
        SmartTags("last_error") = "Folder missing:" & sFolder
        Err.Clear
        ActivateScreen sScreenErr, 0
        Exit Function
    End If
    Err.Clear
    On Error Goto 0
    
    ' File open, mode 1 = Input, lock 1 = Lock Read
    On Error Resume Next
    fo.Open sFolder & "\" & sFile, 1, 1
    If Err.Number <> 0 Then
        SmartTags("last_error") = "Open:" & Err.Number & " "& Err.Description
        Err.Clear
        ActivateScreen sScreenErr, 0
        Exit Function
    End If
    On Error Goto 0
    
    ' Read first line, with EOF guard
    On Error Resume Next
    If fo.EOF Then
        sResult = ""
    Else
        sResult = fo.LineInputString
    End If
    If Err.Number <> 0 Then
        SmartTags("last_error") = "Read:" & Err.Number
        Err.Clear
        fo.Close
        ActivateScreen sScreenErr, 0
        Exit Function
    End If
    On Error Goto 0
    
    ' Write and clean up
    SmartTags(sTagName) = sResult
    fo.Close
    SmartTags("last_error") = ""
    ActivateScreen sScreenOK, 0
End Function

Call from a button or scheduler with the project-wide path:

ReadFirstLineAndRoute "\Storage Card\1234", "txt_file.txt", "yourTag", "Screen_1", "Screen"

11. Verification Checklist

  1. Compile the project in TIA Portal; VBS errors appear under Info > Compile only for syntax, not for runtime COM errors.
  2. Download to the panel and open a diagnostics screen that displays SmartTags("last_error").
  3. Trigger the function. A clean run sets last_error to empty and routes to Screen_1.
  4. Remove the file and trigger again. The error screen should show the diagnostic string with error 53.
  5. Remove the parent folder and trigger again. The error screen should show "Folder missing".
  6. Restore both, schedule the function from the Scheduler at 1 s, and confirm that two consecutive calls do not collide (no error 55).

12. Standards and Cross-References

Siemens VBS on the Comfort Panel is a closed runtime and is not documented by an external standards body. The closest general references are:

  • Siemens FAQ 106501825How do you use the FileSystem object in WinCC (TIA Portal) for a script? (PC runtime only).
  • Siemens FAQ 59604194How can you access files and directories with VBS on a Comfort Panel?
  • Siemens FAQ 26107211How can you run a VBS function in WinCC Comfort/Advanced periodically or time-controlled?
  • SIMATIC HMI WinCC Comfort/Advanced V15.1 — Programming and Operating Manual, section 9.5 "VBScript object model".
Note on firmware support: FileCtl.File.LineInputString and FileCtl.FileSystem.Dir have been available on every Comfort Panel firmware since V13.0.1. The lock parameter has been permissive (accepts 0/1/2/3) since V14. There is no need to downgrade the panel firmware to use these calls.

Why does my script run in the simulator but fail on the TP1200 with "ActiveX component can't create object"?

The simulator uses the host Windows libraries and resolves CreateObject("Scripting.FileSystemObject") against Microsoft Scripting Runtime. The Comfort Panel runtime uses the vendor-supplied FileCtl namespace. Replace both calls with FileCtl.FileSystem and FileCtl.File as documented in Siemens FAQ 59604194. There is no automatic fallback between the two namespaces.

What is the correct Open mode for reading a file on a Comfort Panel?

Use mode 1 for input (read), 2 for output (overwrite), and 8 for append. The lock parameter accepts 0 (no lock), 1 (lock read), 2 (lock write), 3 (lock both). For a read-only file use fo.Open path, 1, 1. Using 0 as the mode returns error 0x80070057.

Why does the first click after panel boot return a blank tag value?

The FileCtl COM service is instantiated on the first call. Add a priming call such as fso.Dir("\") at the start of the function, or trigger the function once from a Scheduler at boot. Caching the fso object as a project-level variable is not reliable across firmware versions — re-create it on every call.

Can I use a network share path like \\server\share\file.txt on a Comfort Panel?

Yes, but the runtime must be authenticated to the share. Configure credentials in the panel's Control Panel > Network > User Accounts and use a UNC path with double backslashes (\\server\share\file.txt in VBS, which is a single backslash at runtime). Anonymous shares work without configuration. Network latency on the first call can exceed 200 ms; use a Scheduler for non-interactive reads.

How do I trigger the same VBS function from both a button and a scheduler?

Place the function in the project-wide Scripts node, not on a screen. From the button Click event call the function by name with one line. From the Scheduler create a new scheduled task with the trigger "Cyclic" or "Once at startup" and the action "Run script", selecting the same function. Do not duplicate the logic in two places — a project-wide function ensures the same code path and the same COM initialization.

Back to blog