Writing String Tags to WinCC Runtime with SetTagChar

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

Siemens WinCC Runtime (both the classic TIA Portal WinCC RT and the newer WinCC Unified RT) exposes tag values to HMI screens through a project-wide tag database. Text strings are stored in WString or String tags and can be written to at runtime using a small set of scripting functions. The most common function in WinCC RT Professional / Comfort / Advanced is SetTagChar, which accepts a tag name and a string value, resolves the tag, and posts the new value to the runtime tag manager.

This article covers three implementation paths:

  1. Write a string from a button event using SetTagChar in VBScript (WinCC RT Professional, Advanced, Comfort).
  2. Bind a static-text object's Output property to a tag and overwrite the tag on a mouse/keyboard event (WinCC RT Comfort / Unified).
  3. Write a string from JavaScript in WinCC Unified RT V17+ using HMIRuntime.Tags.SysFct.SetTagValue.
Note: The function name SetTagChar is historical. Internally it always handles wide-character strings (UTF-16). The "Char" suffix is a legacy artifact from WinCC V6 / V7 days when 8-bit string tags existed. In TIA Portal, you still call SetTagChar from VBScript and it accepts WString tags transparently.

Prerequisites

Item Requirement
Engineering software TIA Portal V16 / V17 / V18 / V19 / V20 with WinCC Comfort, Advanced, or Professional option installed
Runtime target WinCC RT Advanced, WinCC RT Professional, WinCC Unified PC RT, or Unified Comfort Panel (MTP/MTP2200 / Unified Comfort)
Runtime license WinCC RT minimum; for Unified scripting, a Unified PC RT 1500+ tag license is required
Tag type Tag must be defined as WString (default) or String in the HMI tag table
Scripting runtime VBScript for WinCC RT Professional / Advanced; JavaScript (ECMAScript 2021) for WinCC Unified
User authorization Operator station must be in the "Logged on" state and have write rights for the tag

Verify your engineering installation supports scripting on the selected panel: in the TIA Portal project tree, expand the HMI device, then Runtime settings > Services; on Comfort and Unified Panels, enable VBScript runtime (or JavaScript runtime on Unified). On WinCC RT Professional, scripting is always available.

Step 1 - Create the HMI Tag

  1. Open the HMI tag table in TIA Portal: Project tree > HMI_1 > HMI tags > Default tag table.
  2. Add a new tag named gs_tag_char (or any HMI-compliant name - no spaces, no special characters other than _).
  3. Set Data type to WString[254] for typical name fields. The length parameter is the maximum character count; Siemens HMI tags use UTF-16 so each character costs 2 bytes of process-image memory.
  4. Set the Connection to the internal HMI connection if the tag is local, or to a PLC connection (S7-1200/1500 OPC UA / S7 / Modbus TCP) if it is to be forwarded to the controller.
  5. Compile and download the HMI station to the runtime.
Tag-name pitfall: WinCC tags are case-sensitive at runtime. The string passed to SetTagChar must match the name in the tag table exactly, including the same casing used in the Engineering view.

Step 2 - Configure the Static Text Object

  1. In the screen, add a Text field / Static text object and rename its Object Name property to something stable, for example TxtName. Object names become script handles and must be unique within the screen.
  2. Open the Properties > General > Output (or Text) property and click the small lightning-bolt icon to bind the property to a tag.
  3. Select HMI tag > gs_tag_char and confirm.
  4. Set Properties > General > Mode to Output (read-only). This is the default for static text; the object will refresh automatically when the tag value changes.

When the tag gs_tag_char is updated from any source - script, PLC, or another screen object - the static text will display the new content on the next cycle of the HMI runtime (typically 100-300 ms depending on the configured acquisition cycle).

Step 3 - Write the String with SetTagChar (WinCC RT VBScript)

Bind a button click event to a VBScript action that calls SetTagChar:

  1. Drag a Button object onto the screen and rename it to BtnWriteTag.
  2. Open Properties > Events > Click and add a new VBScript function.
  3. Paste the following code:
' VBScript - WinCC RT Professional / Advanced / Comfort
' Writes a constant string to an HMI tag at runtime.

Sub BtnWriteTag_Click(ByVal Item)
    Dim sValue
    sValue = "Example Text"
    
    ' SetTagChar(tagname, value)
    ' Returns SmartTag error code:
    '   0  = success
    '   1  = type mismatch (tag is numeric)
    '   2  = tag not found
    '  -1  = no connection / runtime not running
    Dim rc
    rc = SmartTags("gs_tag_char").Write("Example Text")
    ' Equivalent direct call:
    ' rc = SetTagChar("gs_tag_char", "Example Text")
    
    If rc <> 0 Then
        ShowSystemAlarm("SetTagChar failed, error=" & rc)
    End If
End Sub

Two calling styles are supported on WinCC RT Professional and above:

Style Syntax Returns Available on
SmartTag (recommended) SmartTags("gs_tag_char").Write(value) HRESULT (0 = OK) WinCC RT Professional, Advanced, Comfort from TIA V14 SP1
Direct call SetTagChar("gs_tag_char", value) Integer error code WinCC RT Professional, WinCC V7 legacy
Read back result = SmartTags("gs_tag_char").Read() String All TIA WinCC RT variants

Step 4 - Allow Operator Keyboard Input into the Tag

When the requirement is "operator clicks the field, types a new value, presses Enter, and the new text is written to the tag", the cleanest solution is the IO field object, not a static text. The IO field already contains a built-in editor and a configured process value.

  1. Replace the static text with an IO field.
  2. Set Properties > General > Mode to Input/Output.
  3. Bind the Process value property to the tag gs_tag_char.
  4. Set Properties > Appearance > Display format to String.
  5. Optionally, set Properties > Events > Change to a VBScript that validates the string length or character set:
Sub IOField_Change(ByVal Item)
    Dim s
    s = SmartTags("gs_tag_char").Read()
    If Len(s) > 254 Then
        ShowSystemAlarm "Name too long (max 254)"
        SmartTags("gs_tag_char").Write Left(s, 254)
    End If
End Sub

If a static text must be used, configure the text object's Properties > General > Text as a tag pointer to gs_tag_char and add a hidden IO field on top of it; on focus, the operator types into the IO field and the change is mirrored into the tag, which then refreshes the static text.

Step 5 - Write the String from C / ANSI-C (Legacy)

On WinCC V7 or older TIA projects using C scripts:

/* ANSI-C snippet - WinCC V7 / early TIA Comfort */
#include "apdefap.h"
void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{
    SetTagChar("gs_tag_char", "Example Text");
}

SetTagChar in C takes a char* pointer to a NULL-terminated buffer. The function copies up to the tag's configured length minus one character; the remainder is discarded silently.

Step 6 - Write the String from JavaScript (WinCC Unified RT V17+)

WinCC Unified uses an ECMAScript-based scripting environment with a fundamentally different API. The SetTagChar VBScript function does not exist on Unified. Use HMIRuntime.Tags.SysFct.SetTagValue or the Tags() collection:

// JavaScript - WinCC Unified RT V17 / V18 / V19 / V20
// Trigger: Button 'BtnWrite' Click event

import "HMIRuntime";  // optional in Unified V18+, included by default

export function BtnWrite_OnClick(mouseX, mouseY) {
    const value = "Example Text";
    
    // Async style (recommended, returns Promise)
    HMIRuntime.Tags.SysFct.SetTagValue("gs_tag_char", value)
        .then(function (result) {
            if (result !== 1) {
                HMIRuntime.Trace("SetTagValue failed, result=" + result);
            }
        })
        .catch(function (err) {
            HMIRuntime.Trace("SetTagValue exception: " + err);
        });
    
    // Sync style (V18+, blocks UI thread for <5 ms typically)
    // const rc = HMIRuntime.Tags.SysFct.SetTagValue("gs_tag_char", value);
}

Result codes for the Unified API:

Return value Meaning
1 Success - value accepted by runtime tag manager
0 Failure - tag not found, or quality is bad
-1 Parameter error (null pointer, wrong type)

To read text files from disk and push their content into a tag (the use case covered by Siemens' official example for V20), see: Reading and writing text files (RT Unified) - WinCC Unified V20 scripting documentation. The example uses HMIRuntime.Trace(text) to confirm execution and combines the Node-style fs callback pattern with SetTagValue.

Step 7 - Trigger Automatic Updates on Tag Change

The static text field refreshes automatically once it is bound. The refresh cadence is controlled by the tag's Acquisition cycle (default 1 s) and by the connection's update rate. To make the visual feedback feel "instant":

  1. Open the HMI tag gs_tag_char.
  2. Set Acquisition mode to Cyclic continuous.
  3. Set the Acquisition cycle to 100 ms.
  4. Recompile and download the HMI station.
Caution: Reducing the acquisition cycle below 100 ms for many tags can saturate the OPC UA / S7 connection and cause high CPU load on Comfort panels. Keep the number of high-frequency tags below ~200 per panel.

Step 8 - Verification

After the project has been compiled and downloaded, run the following checks:

  1. Start the WinCC Runtime (or Unified RT) and navigate to the screen containing TxtName and BtnWriteTag.
  2. Click the button. The static text must change to Example Text within one acquisition cycle (≤ 1 s).
  3. Open the online tag diagnostics: Project tree > HMI_1 > Online > Tag simulation, and read the current value of gs_tag_char. It must read Example Text.
  4. In the runtime log window, confirm no VBScript / JavaScript errors are reported. The WinCC RT Professional log file is at C:\ProgramData\Siemens\Automation\WinCCRT\Logs\WinCC_Sys_.log; the Unified log is at C:\ProgramData\Siemens\Automation\WinCCUnified\Logfiles\RT-Log.txt.
  5. If the tag is connected to a PLC, use TIA Portal's Online & Diagnostics on the S7-1200 / S7-1500 to confirm the value reached the controller as a WString DB element.

Troubleshooting Matrix

Symptom Likely cause Fix
Static text does not change after script runs Tag name mismatch (casing, leading/trailing space) Match the exact string in SmartTags("...") to the HMI tag table name
SetTagChar returns error 1 Tag defined as Int or Real Change tag data type to WString[254]
SetTagChar returns error 2 Tag not present in the active runtime project Recompile and reload the HMI station, ensure tag is not "hidden"
Script does not fire on button click Button Authorization property blocks the operator Lower authorization level on the button event or grant the user group write rights
Text appears garbled (mojibake) PLC sends a different encoding than the HMI expects Set both sides to UTF-16 / WString; never connect a STRING (UTF-8) S7 variable to a WString HMI tag without an explicit conversion block
Unified: SetTagValue Promise rejects JavaScript runtime disabled in project Enable Runtime settings > Services > JavaScript runtime on the Unified device
Unified: value written, but PLC shows 0x00 WString adapter in PLC DB not configured In the S7-1500 DB, use the WSTRING[254] type and ensure the HMI connection uses the BLOB-optimized symbol access
IO field rejects text > 254 chars Tag length shorter than input Increase tag length or trim the value in the Change event
Performance drops after enabling SetTagChar polling Acquisition cycle too short for the tag count Increase cycle to 500 ms; consolidate multiple strings into a single DB block

Performance and Sizing Notes

String handling on a Comfort Panel is bounded by three resources:

  1. Process image memory: each WString tag reserves 2 × (length + 1) bytes. 100 tags of WString[254] consume ~51 KB of the HMI tag database.
  2. Script execution budget: VBScript on a Comfort Panel is single-threaded; a SetTagChar call typically completes in 5-15 ms, but a tight loop writing 1000 strings can stall the screen for 10+ seconds. For bulk writes, use a single tag-array write from a PLC instead of looping in the script.
  3. Network bandwidth: an S7-1500 ↔ Comfort Panel connection on 100 Mbit Ethernet can carry ~30,000 WString characters per second at a 100 ms acquisition cycle before saturating.

On Unified PC RT the limits are far higher (multi-threaded JavaScript, no per-tag script budget), but the tag write is still asynchronous: the SetTagValue Promise resolves on the next OPC UA publish cycle (default 100 ms).

Security and Authorization

Writing tags with SetTagChar bypasses the operator's input authorization on the IO field; the runtime still enforces the script execution authorization, which by default is granted to Administrator only. To let operators trigger the write from a button:

  1. Open Project tree > HMI_1 > User administration > Groups.
  2. Add the operator group (for example Group_3) and grant the right Operator - Write tags via script.
  3. On the button, set Properties > Security > Authorization to Group_3.
  4. Recompile and download.

For audit trail, enable Runtime settings > Logging > Audit and tag the script's relevant events. Each SetTagChar call can be wrapped in TraceText to log to the Audit Viewer.

Platform-Specific Notes

Platform Script language Function name Min firmware
Comfort Panel (TP700 / TP1500 / TP2200) VBScript SetTagChar, SmartTags(...).Write V14 SP1+
WinCC RT Advanced (PC) VBScript, C Same as Comfort V14 SP1+
WinCC RT Professional (PC) VBScript, C, VB, C# SetTagChar + HMIRuntime.Tags(...).Write V16+ for the C# style
Unified Comfort Panel (MTP) JavaScript HMIRuntime.Tags.SysFct.SetTagValue V17+ (GA) firmware 17.0.0.0
Unified PC RT (UPC) JavaScript, C# Same as MTP V17+ runtime 17.0.0.1
Legacy WinCC V7.4 / V7.5 VBScript, C, VB SetTagChar (legacy form, no SmartTags) WinCC V7.0+

Unified RT V20 introduces structured tag access via the Tags("MyStruct.MyField") dot notation in both JavaScript and the property binding editor. For details on reading and writing text files and pushing the content into a tag, see the Siemens official example: Reading and writing text files (RT Unified).

Field-Proven Patterns

Pattern A - Confirmation prompt before overwrite. Use ShowPopup with two buttons before the write, to prevent accidental renaming of an asset:

Dim rc
rc = ShowPopup("Overwrite name?", "Yes", "No", "", 0)
If rc = 1 Then SmartTags("gs_tag_char").Write "NewName_42"

Pattern B - Append a timestamp to a logging tag. Useful for operator-action audit strings. Be aware that WString concatenation in VBScript is slow on Comfort Panels; use the Format function rather than manual & concatenation if the tag is hot-path:

Dim s
s = SmartTags("gs_log").Read()
SmartTags("gs_log").Write s & ";" & Format(Now, "hh:nn:ss") & ":" & SmartTags("gs_tag_char").Read()

Pattern C - Multi-language name table. Store the operator name list in the PLC and only write the selected index from the HMI; the PLC returns the localized WString back to the HMI. This avoids the 254-character limit per tag and is the recommended approach for global deployments.

FAQ

Why does my static text not update when I change the tag from a script?

The text field is not bound to the tag. Open the text object's Properties > General > Text (or Output) property and click the lightning-bolt icon to select the HMI tag. After reloading the screen, the field will reflect the value on the next acquisition cycle (typically 100 ms to 1 s).

What is the difference between SetTagChar and SmartTags("...").Write?

On WinCC RT Professional and TIA V14 SP1+, both work. SetTagChar("name", value) is the legacy direct call and returns an integer error code (0 = OK). SmartTags("name").Write value is the modern object-style call and returns an HRESULT. Prefer SmartTags in new projects because IntelliSense in TIA Portal's VBScript editor recognizes it.

Can I write a string to a WinCC RT tag from a Siemens S7-1500 PLC?

Yes. Create an HMI tag of type WString[254] and connect it to a DB element of type WSTRING[254] in the S7-1500. The PLC updates the HMI tag on the next acquisition cycle. No script is needed; the value flows automatically. This is the recommended method for most name-plate or recipe-header data.

How do I let the operator type a new name on the HMI screen?

Use an IO field with Mode = Input/Output and a String display format. Bind its Process value to the tag. The IO field handles the on-screen keyboard on Comfort Panels and the hardware keyboard on PC-based runtime. A static text cannot accept keyboard input on its own - pair it with an IO field if you also need a read-only display.

Does SetTagChar work in WinCC Unified?

No. WinCC Unified uses ECMAScript (JavaScript) and exposes a different API: HMIRuntime.Tags.SysFct.SetTagValue(tag, value). The call is asynchronous and returns a Promise that resolves to 1 on success. For full examples, see the Siemens documentation Reading and writing text files (RT Unified).

Back to blog