Writing Data to TXT Files with VBScript in WinCC TIA Portal

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

Writing Data to TXT Files with VBScript in WinCC TIA Portal

This technical reference explains how to persist tag values, alarms, and runtime data to a .txt file from a Siemens SIMATIC HMI panel or WinCC Runtime PC using VBScript inside the TIA Portal scripting environment. The technique relies on the legacy FileCtl.File COM object that ships with WinCC Comfort/Advanced/Professional and the WinCC Runtime PC, and it is fully supported in TIA Portal V13 through V17 SP1 (and forward to V19 with the same method signature). The reference covers runtime paths, mode constants, error handling, multi-line records, append vs. overwrite, and the most common failure modes encountered during HMI commissioning.

Scope. This document addresses runtime-side data archiving, not recipe data logs. Recipe storage should use the TIA Portal Recipes view and the HmiRuntime.Recipe object. For raw data streaming use the built-in data logging of WinCC where possible; use VBScript only when the schema is custom.

1. Overview of the FileCtl Object in WinCC TIA Portal

The FileCtl.File object is an ActiveX/COM component delivered with the WinCC Runtime (both RT Professional and RT Advanced) and with every Comfort/Advanced Panel firmware image. It exposes the minimal surface required to open, write, and close a text file. The object is created with the standard VBScript CreateObject call:

Set fo = CreateObject("FileCtl.File")

The ProgID FileCtl.File resolves to the Windows registry on PC Runtime, and to the WinCC embedded scripting host on panel targets. The object does not need a separate installation step; it is registered when the runtime starts. The full object model for panel-based scripting is documented in the Siemens function manual WinCC TIA Portal Engineering V17 - Scripting (VBScript) and the older but still applicable WinCC TIA Portal V13 SP1 - Programming and Reference Manual.

2. Prerequisites

  1. TIA Portal V13 SP1 minimum. V13 SP1 introduced the consolidated VBScript editor for Comfort Panels. Earlier V13 builds may require a hotfix (ESR13_SP1_HF2) to expose FileCtl.File reliably on PC Runtime.
  2. Runtime project compiled and downloaded. The script executes only on the target; it is not run in the TIA Portal PLCSIM-style HMI simulation for panels. The PC Runtime can be tested with the WinCC Runtime Advanced simulator, but only if the file path is a valid Windows path (e.g., C:\Logs\), not a panel path.
  3. Write permission on the target folder. On a panel, the system account is fixed; on a PC runtime, the user account that starts the runtime must have write access. See Section 6.
  4. VBScript configured on the HMI. Open the project in TIA Portal, select the HMI device, and confirm in Runtime Settings > Language & Font that VBScript is enabled. Comfort Panels ship with VBScript disabled by default; enable it in the device configuration.

3. The Working Script

The following script is a hardened version of the original sample, with the known errors corrected. It opens C:\Text.txt in append mode, writes a line containing a tag value, then closes the file. Drop it into a Scheduled Task, a Value Change event, or call it from a button click.

<!-- Save this as a function in the Scripts module -->
Function SaveLineToFile(sFilePath, sLine)
    Dim fo, mode, ErrNumber, ErrDescription
    
    mode = 8           ' 8 = append, 2 = overwrite, 1 = read
    Err.Clear
    
    Set fo = CreateObject("FileCtl.File")
    If Err.Number <> 0 Then
        ShowSystemAlarm "Error creating FileCtl: #" & Err.Number & " " & Err.Description
        Exit Function
    End If
    
    fo.FileName = sFilePath
    fo.mode = mode
    fo.open sFilePath, mode
    If Err.Number <> 0 Then
        ShowSystemAlarm "Error opening file: #" & Err.Number & " " & Err.Description
        Set fo = Nothing
        Exit Function
    End If
    
    fo.LinePrint(sLine)
    If Err.Number <> 0 Then
        ShowSystemAlarm "Error writing line: #" & Err.Number & " " & Err.Description
        fo.Close
        Set fo = Nothing
        Exit Function
    End If
    
    fo.Close
    Set fo = Nothing
    ShowSystemAlarm "Line saved to " & sFilePath
End Function

Call the function from a button event (e.g., Click) using:

Call SaveLineToFile("C:\Text.txt", _
    Now & vbTab & SmartTags("Tag1") & vbTab & SmartTags("Tag2"))

4. Open Mode Constants

The mode parameter passed to fo.open selects how the file is opened. The values are constants inherited from the legacy WinCC Flexible FileCtl control:

Mode Constant Behavior Typical Use
1 READ Opens existing file for reading only; missing file raises error 53 Loading configuration data
2 WRITE Creates new file or overwrites existing; deletes prior content One-shot reports
8 APPEND Opens existing file or creates new; writes at end Continuous data log
32 BINARY Binary read mode Not used for TXT

For a continuous measurement log, always use mode 8 (append). Mode 2 (write) destroys prior records, which is rarely desired in a production HMI.

5. Path Rules: Panel vs. PC Runtime

The single most common failure on the original poster's script is an unreachable path. Panel Runtime and PC Runtime have very different available file systems.

5.1 PC Runtime (WinCC Runtime Advanced / Professional on a Windows host)

The runtime runs as a standard Windows process. The script can write to:

  • Any fixed drive: C:\Logs\Archive.txt
  • USB sticks mounted at runtime: E:\Backup.txt
  • Network shares if the runtime service account has access: \\SERVER\share\log.txt

Avoid mapped drives (e.g., H:\) because the runtime service may not inherit the user session mappings. Use UNC paths.

5.2 Panel Runtime (Comfort / Unified Comfort)

Comfort Panels run a Windows Embedded Compact 7 (WEC7) or, on newer Unified Comfort Panels, Windows 10 IoT Core. The available paths are restricted:

Path Available on Panel? Notes
\Storage Card SD\log.txt Yes (Comfort) SD card must be present and write-enabled
\USB\Storage\log.txt Yes (with USB stick) Only when stick is plugged before runtime start
\Flash\Internal\log.txt Limited Internal flash has limited write cycles; not recommended for logs
C:\Text.txt No (WEC7) Path is wrong; will produce "file not found" or silent failure

The original poster's path c:\Text.txt is valid on PC Runtime but invalid on most Comfort Panels. This is the primary reason the script "doesn't create the file."

6. Permission and Folder Existence

FileCtl.File will not create intermediate directories. If C:\Logs does not exist, fo.open raises error 76 (Path not found) on PC, or returns silently without writing on panel targets. Always pre-create the directory or use a path known to exist.

Pre-create the folder from the script. On PC Runtime, use CreateObject("Scripting.FileSystemObject") with CreateFolder to ensure the path exists before writing. On panel targets, the directory \Storage Card SD\ always exists if an SD card is inserted, so you can write directly into it.

7. Known Errors and Their Meaning

The Err.Number values returned by the WinCC VBScript host are the standard VBScript runtime errors. The following list covers the codes typically raised by FileCtl.File operations:

Err.Number Description Cause Fix
429 ActiveX component can't create object FileCtl not registered (PC) or panel firmware older than required Re-install runtime / update panel image
53 File not found Path does not exist or mode 1 with no prior file Check path, switch to mode 8
70 Permission denied File locked by another process or read-only SD Close other handles; unlock SD write-protect switch
76 Path not found Parent folder does not exist Create folder first
3219 Operation is not allowed in this context Call to LinePrint before open Always call open first

For the full VBScript error reference, see the Microsoft documentation on VBScript Error Numbers (the WinCC host implements the same numeric error table).

8. Multi-line Records and Delimiters

To produce a CSV-like file, use vbTab or ; as the column delimiter, and call LinePrint once per record. The LinePrint method appends a CRLF automatically, so the next call starts a new line.

Dim sLine, sPath
sPath = "C:\Logs\Measure_" & Format(Now, "YYYYMMDD") & ".txt"
sLine = SmartTags("MachineID") & ";" & _
        Format(Now, "YYYY-MM-DD HH:NN:SS") & ";" & _
        SmartTags("TempC") & ";" & _
        SmartTags("PressureBar")
Call SaveLineToFile(sPath, sLine)

For tab-separated output (Excel-friendly), replace the ; with vbTab and import the file with the wizard, which will place each column into its own cell automatically.

9. Verification Steps

After deploying the project to the HMI or PC Runtime, perform the following verification sequence:

  1. Trigger the script (button or scheduled task) and observe the ShowSystemAlarm message in the alarm line. A successful write shows "Line saved to ..."; a failure shows the specific error code.
  2. Open the target file in a text editor (Notepad, Notepad++) and confirm the line was appended, not overwritten.
  3. Cycle the trigger five times and confirm five distinct timestamps are written when using mode 8.
  4. Stop the runtime, restart it, and trigger the script again. Confirm the file is preserved across the runtime restart (this validates the path is on persistent storage, not RAM).
  5. On a panel, remove the SD card and confirm the system alarm reports a clear error rather than hanging the runtime.

10. Troubleshooting Matrix

Symptom Likely Cause Diagnostic Resolution
No file appears Path invalid on panel target Check \Storage Card SD\ exists Rewrite path to panel syntax
Error 429 on PC FileCtl not registered Run regedit and search "FileCtl" Repair WinCC Runtime installation
Only first record written File handle not closed Check fo.Close in script Always close in error path too
Garbled characters Encoding mismatch Open with Notepad; check ANSI vs UTF-8 Use FileCtl default ANSI on WinCC
Slow performance File opened on every event Profile with GetTickCount Open once per session, close on shutdown
File locked Previous runtime crashed Check for stray .lck in folder Delete lock file or reboot
Script compiles, doesn't run Wrong event wired Trace event in TIA Portal log Re-assign script to correct event

11. Performance Considerations

On a Comfort Panel with WEC7, a single LinePrint call typically takes 5-15 ms including file system journaling. For high-frequency data (e.g., 100 Hz vibration), this is not viable; instead, batch values into a string and write every Nth cycle. For a typical 1 Hz production log, the overhead is negligible.

On a PC Runtime, the cost is dominated by antivirus scanning. Exclude the log directory from real-time AV inspection to avoid I/O stalls of several hundred milliseconds.

12. Migrating from WinCC Flexible to TIA Portal

Projects migrated from WinCC Flexible V11 SP2 forward to TIA Portal V13/V14 retain the same FileCtl.File object. The original poster's code from a WinCC Flexible thread worked unchanged in TIA Portal V13, with one caveat: in V13 SP1 and later, the mode property assignment is automatic; explicitly setting fo.mode = 8 is harmless but not required. The open call still expects the path as the first argument and the mode as the second.

For projects that must support both TIA Portal V13 and V17/V18/V19, the script in Section 3 is forward-compatible because the FileCtl.File ProgID has remained stable since WinCC Flexible 2008.

Unified Comfort Panels. On MTP/UTP panels (Unified Comfort, TIA Portal V16+), FileCtl.File is still available, but Siemens recommends the HMIRuntime.FileSystem JavaScript API for new development. The VBScript path remains valid for legacy code migration.

13. Security and Operational Notes

  • Do not write to the panel's internal flash for routine logging. The flash has a finite write endurance (typically 100,000 cycles per sector) and a production log will exhaust it within months.
  • Always wrap fo.open in error handling; a script that aborts mid-write can leave a zero-byte or truncated file.
  • For regulated environments (FDA 21 CFR Part 11, EU Annex 11), the FileCtl.File output alone does not satisfy audit trail requirements. Add a hash or signed timestamp via an external audit service.
  • Restrict the file path to a known directory; never accept the path from a tag value without sanitization, to avoid path traversal attacks on a PC runtime exposed to the plant network.

14. Related Objects and Methods

For full data logging, the VBScript API exposes a richer set of objects that pair with FileCtl.File:

Object Use Reference
FileCtl.File Simple line-based I/O This document
Scripting.FileSystemObject Folder operations, binary I/O Microsoft FSO docs
HMIRuntime.Tags Read/write PLC tags Siemens manual 109755202
HMIRuntime.Alarm Read active alarms for logging Same manual

FAQ

Why does my VBScript not create the TXT file on a Comfort Panel?

The path C:\Text.txt is a Windows PC path. On a Comfort Panel, write to \Storage Card SD\Text.txt (with an SD card inserted) or \USB\Storage\Text.txt (with a USB stick). The panel filesystem is not mounted as C:\.

Which open mode preserves existing data?

Use mode 8 (append). Mode 2 (write) creates a new file or overwrites the existing one. Mode 1 is read-only and raises error 53 if the file does not exist.

What does Error 429 mean when creating FileCtl.File?

Error 429 is "ActiveX component can't create object." On a PC runtime, the FileCtl OCX is not registered; repair the WinCC Runtime installation. On a panel, the firmware image is older than required for VBScript; update the panel image via ProSave.

Can I write binary data with FileCtl.File?

No. FileCtl is line-oriented and ANSI text. For binary I/O use the standard Scripting.FileSystemObject on PC Runtime. FileCtl supports LinePrint and LineInput only.

Is FileCtl.File supported in TIA Portal V18 and V19?

Yes. The ProgID has remained stable since WinCC Flexible 2008 and is still present in TIA Portal V19 WinCC Runtime Advanced and the Unified Comfort Panel scripting host. New development on Unified Comfort should use the JavaScript FileSystem API, but the VBScript path is fully supported for legacy migration.

Back to blog