Opening Excel Files from WinCC Button Click VBS and C Scripting

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

Launching an external application such as Microsoft Excel from a Siemens WinCC HMI/SCADA runtime is a recurring operator-panel requirement: technicians need one-click access to production reports, batch logs, trend archives, and shift handover spreadsheets. WinCC Runtime exposes two scripting environments that can spawn child processes: ANSI-C scripts under the legacy ProgramExecute() API, and VBScript (VBS) using the Windows Script Host WScript.Shell COM object. Both APIs are documented in the Siemens WinCC Information System and remain supported in WinCC V7.4 through the current TIA Portal WinCC Unified runtime, although the recommended scripting engine in modern projects is VBS within the WinCC Graphics Designer.

This reference consolidates the working code patterns, clarifies the exact path/argument escaping rules that drive most field failures, and adds diagnostic steps for WinCC 5.1, V7.0, V7.4, and WinCC Unified PC RT. Where the discussion below shows specific Office install paths, the path segment (Office12 = Office 2007, Office14 = Office 2010, Office15 = Office 2013, Office16 = Office 2016/2019/2021/365) must match the build installed on the engineering station.

Prerequisites

  1. WinCC Runtime Professional / WinCC Runtime Advanced licensed and active on the HMI station. Confirm in WinCC Explorer under Project Properties > Runtime.
  2. Microsoft Excel installed locally (the path used in the script must match the installed architecture: 32-bit Office under C:\Program Files (x86)\Microsoft Office\..., 64-bit Office under C:\Program Files\Microsoft Office\...).
  3. Graphics Designer open with the target picture, or the Unified RT project loaded in a web client.
  4. For VBS: the Microsoft Scripting Runtime and the WScript.Shell COM automation server registered. Both ship with Windows; verify with regedit > HKEY_CLASSES_ROOT\WScript.Shell.
  5. For ANSI-C: include the apdefap.h and msproto.h headers from the WinCC installation; the ProgramExecute() function resides in the toolspro.lib.
  6. The Excel file accessible from the runtime user context. UNC paths are recommended on multi-user stations to avoid drive-letter dependencies.

Method 1: ANSI-C with ProgramExecute

The C-API ProgramExecute() launches an external program synchronously and is the canonical approach in legacy WinCC 5.1, V6.x, and V7.0 projects. The function prototype is:

BOOL ProgramExecute(LPCTSTR lpProgram);

lpProgram must contain the executable path followed by a single ASCII space and the full file path. The space is mandatory; omitting it causes the OS to interpret Excel.exeD:\OUT\report.xls as one filename, which is the single most common cause of the "button does nothing" field fault.

Working C Examples

ProgramExecute("C:\\Program Files (x86)\\Microsoft Office\\Office12\\EXCEL.EXE D:\\OUT\\report.xls");

The above targets 32-bit Office 2007. For Office 2010 (Office14):

ProgramExecute("C:\\Program Files\\Microsoft Office\\Office14\\EXCEL.EXE D:\\OUT\\report.xls");

For the 32-bit Office 2010 default path on a 64-bit OS:

ProgramExecute("C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE D:\\OUT\\report.xls");

Minimal C Action Script

  1. In Graphics Designer, select the button > Properties > Events > Mouse > Mouse Click.
  2. Choose C-Action and paste the ProgramExecute line above.
  3. Compile (Ctrl+F7) and verify the return window shows "0 errors, 0 warnings".
Always escape backslashes as \\ in C string literals. A single \ produces a stray escape sequence and the call will not compile or will silently fail at runtime.

Method 2: VBScript with WScript.Shell

VBS is the preferred scripting language in WinCC V7.x and Unified PC RT. The WScript.Shell COM object exposes a Run method that mirrors ProgramExecute with better diagnostics and parameter typing. A canonical button-click handler is:

Dim oShell
Set oShell = CreateObject("WScript.Shell")
oShell.Run "EXCEL.EXE D:\OUT\report.xls", 1, False
Set oShell = Nothing

Argument breakdown:

Argument Value Meaning
Command EXCEL.EXE D:\OUT\report.xls Executable followed by a single space and full file path.
WindowStyle 1 Activate and display window (normal focus).
WaitOnReturn False Return immediately, do not block the WinCC picture.

The WindowStyle constants follow the standard Microsoft Wscript.Shell.Run semantics: 0 = hidden, 1 = normal, 2 = minimised, 3 = maximised, 7 = minimised/no focus.

Reading the Excel Path from a WinCC Tag

Hard-coded paths break the moment the operator station changes drive mappings or the report output directory rotates. The robust pattern uses a WinCC internal WString tag that holds the file path. The classic field question is: "why does nothing happen when I concatenate the tag value to EXCEL.EXE?"

Working VBS with WString Tag

Dim oShell
Dim sPath

sPath = SmartTags("HMI_WString_Tag")

Set oShell = CreateObject("WScript.Shell")
oShell.Run "EXCEL.EXE " & sPath, 1, False
Set oShell = Nothing

Three correctness rules apply:

  1. Insert a literal ASCII space (character 0x20) between EXCEL.EXE and the variable. Concatenating without a space yields EXCEL.EXED:\OUT\report.xls, which Windows treats as a single (non-existent) executable. This is the failure mode reported by users who say "not opening any excel application".
  2. The tag value must not contain a leading or trailing space. If the path is configured in the tag from a C-script, strip it with Trim(sPath) in VBS.
  3. Enclose sPath in quotes when it may contain spaces (e.g., "D:\My Reports\Shift Log.xls"):
    oShell.Run "EXCEL.EXE """ & sPath & """

Pre-Flight Validation Pattern

Dim oFSO, oShell, sPath
sPath = Trim(SmartTags("HMI_WString_Tag"))

Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FileExists(sPath) Then
    Set oShell = CreateObject("WScript.Shell")
    oShell.Popup "Report file not found: " & vbCrLf & sPath, 5, "WinCC Report", 48
    Set oShell = Nothing
    Exit Sub
End If
Set oFSO = Nothing

Set oShell = CreateObject("WScript.Shell")
oShell.Run "EXCEL.EXE """ & sPath & """", 1, False
Set oShell = Nothing

This pattern surfaces missing files as a dialog rather than a silent no-op, which is essential in GMP/validated environments where silent failures are audit findings.

Method 3: ProgramExecute with Fully Qualified Path

When the runtime user has limited PATH environment variables or when multiple Office versions are installed, supplying the full executable path is the safest approach:

ProgramExecute("C:\\Program Files\\Microsoft Office\\Office16\\EXCEL.EXE D:\\Reports\\DailyReport.xlsx");

Office16 covers Office 2016, 2019, 2021, and the Click-to-Run installer for Microsoft 365 Apps for Enterprise as of the Office 2024 release branch. Office path constants are documented in the Microsoft Office default installation path KB.

On a 64-bit Windows host with 32-bit Office, the executable lives under C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE (Click-to-Run) or C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE (MSI). Verify by right-clicking the Excel shortcut > Open file location.

Common Office Install Path Reference

Office Version Default Path (MSI) Default Path (Click-to-Run)
Office 2007 (Office12) C:\Program Files (x86)\Microsoft Office\Office12\ Not applicable
Office 2010 (Office14) C:\Program Files (x86)\Microsoft Office\Office14\ Not applicable
Office 2013 (Office15) C:\Program Files (x86)\Microsoft Office\Office15\ C:\Program Files (x86)\Microsoft Office\root\Office15\
Office 2016/2019/2021/365 (Office16) C:\Program Files (x86)\Microsoft Office\Office16\ C:\Program Files (x86)\Microsoft Office\root\Office16\
Office 2024 (Office16) MSI not shipped C:\Program Files\Microsoft Office\root\Office16\ (default 64-bit)

If the script targets a WinCC RT station that may receive Office updates which shift the path, prefer the symbolic EXCEL.EXE without folder prefix and rely on the system PATH. If reliability is paramount, deploy a project constant holding the verified path.

WinCC Version Compatibility Matrix

WinCC Version C Script VBScript Notes
WinCC V5.1 Supported, ProgramExecute only Limited VBS support introduced later Use C actions; verify path layout.
WinCC V6.0 / V6.2 Supported VBS fully supported via CreateObject Standard pattern.
WinCC V7.0 / V7.4 Supported (legacy) Recommended VBS diagnostics shown in APDiag.
WinCC V7.5 SP2 Supported Recommended Same APIs, Office 2019/2021 supported.
WinCC Unified PC RT (TIA V18/V19) Not applicable Supported via JavaScript RT API Use HMIRuntime.Trace + Shell.Application.
WinCC Unified Comfort Panel Not applicable Not available Use the Open file client function instead.

For Unified PC RT projects, the JavaScript equivalent is:

import { Shell } from "@microsoft/office-js";
// or via WScript.Shell analogue
let shell = new ActiveXObject("WScript.Shell");
shell.Run("EXCEL.EXE D:\\Reports\\ShiftReport.xlsx");

See the Siemens WinCC Unified Programming Manual for the runtime scripting reference.

Diagnostic and Debugging Procedures

WinCC V7.x APDiag Trace

  1. Open WinCC Explorer > Computer > APDiag.
  2. Add a new trace entry for Graphics Runtime and Global Script Runtime.
  3. Click the button; APDiag logs the script execution status and any COM error (e.g., 0x80040154 Class not registered).
  4. For VBS specifically, set Debug Level = 2 to capture WScript.Shell.Run HRESULT values.

Standalone Script Test

Before binding the script to a button, validate it in Global Scripts C-Editor or via a Windows-side .vbs file:

Dim oShell
Set oShell = CreateObject("WScript.Shell")
WScript.Echo "Launching..."
oShell.Run "EXCEL.EXE D:\OUT\report.xls", 1, True
WScript.Echo "Returned."

Run with cscript.exe test.vbs from the command line. This isolates whether the failure is in WinCC's script host, the path resolution, or Excel itself.

Sysinternals Process Monitor

Capture the Sysinternals Process Monitor trace filtered on Process Name = EXCEL.EXE while clicking the button. The trace reveals whether CreateProcess is issued, what working directory Windows evaluates, and whether a path-not-found status is returned. This is the most authoritative way to settle "nothing happens on click" tickets.

Security, UAC, and Execution Policy Considerations

  • WinCC Runtime typically runs under a service account or the interactive user. If the runtime is launched as a service, the spawned Excel will be in Session 0 and invisible on the operator desktop. Configure WinCC Runtime to run interactively under the logged-on operator account via Computer > Startup.
  • User Account Control (UAC) is enforced on Windows 10/11 and Windows Server 2019/2022. Excel launches fine; however, paths under C:\Program Files should remain read-only. Writing reports to C:\Reports\ is the supported pattern.
  • Antivirus software may quarantine or sandbox EXCEL.EXE spawned from a non-standard parent. Add the runtime user to the AV exclusion list for the Office install directory.
  • The Excel file format matters: legacy .xls (BIFF8) and modern .xlsx (Office Open XML) are both opened by Excel 2010+. Older .xls written by VFP or classic ASP may need the Microsoft Access Database Engine redistributable installed alongside Office.

Troubleshooting Matrix

Symptom Likely Cause Fix
Button click does nothing, no error Missing space between EXCEL.EXE and file path Insert single ASCII space in concatenation: "EXCEL.EXE " & sPath
VBS error: Class not registered 0x80040154 WScript.Shell COM missing Re-register via regsvr32 wshom.ocx from elevated CMD
VBS error: Permission denied 0x800A0046 Runtime user lacks access to Office folder Grant read on C:\Program Files\Microsoft Office\Office16 or use UNC on shared station
C compile error: Unrecognized escape Sequence Single backslash used in C string Use \\ for every directory separator
Excel opens in background, not visible WindowStyle = 0 or Session 0 isolation Set WindowStyle = 1 and verify WinCC runs in interactive session
Excel opens wrong file or blank Tag value corrupted with leading/trailing space Apply Trim() before concatenation
First click works, subsequent clicks fail Office Click-to-Run virtualisation lock Disable Click-to-Run SharedComponent, use MSI install for runtime stations
Excel does not start, APDiag shows Path not found 0x2 File path uses forward slashes or unmapped drive letter Use backslashes and map the drive or use UNC path

Verification Checklist

  1. Click the configured button in WinCC Runtime. Excel must open within 2-3 seconds showing the target workbook.
  2. Repeat the click three times consecutively. Each click must spawn a new Excel window or activate the existing instance (Excel behaviour: single-instance per file by default).
  3. Edit the HMI_WString_Tag from the WinCC tag simulator to point to a non-existent file. Confirm the script displays a diagnostic dialog or APDiag trace entry; do not allow silent failure.
  4. Reboot the runtime station and re-test. Confirm the script executes under the same user context as the WinCC Runtime service or interactive session.
  5. Inspect the Windows Application event log for any Application Error entries with EXCEL.EXE faulting module; resolve Office repairs if surfaced.

Best Practices for Production Systems

  • Store the report template path in a WinCC internal WString tag configured under Project Properties > Tags; do not hard-code in the script body.
  • For validated environments (FDA 21 CFR Part 11, GAMP 5), use the pre-flight FileSystemObject validation pattern and log every successful launch via an internal Binary tag.
  • Prefer EXCEL.EXE without folder prefix to remain agnostic to Office updates, but always supply the explicit /e switch if Excel should launch without a new blank workbook default. The default EXCEL.EXE file.xlsx opens the file as expected.
  • When opening read-only dashboards, append the /r switch: "EXCEL.EXE /r \"" & sPath & "\"" forces Excel into read-only mode, eliminating accidental overwrites.
  • For unattended Windows servers running WinCC Runtime as a service, schedule Excel reports via Windows Task Scheduler rather than launching from the HMI button; Service-Context UAC rules make interactive launches unreliable.

Why does my WinCC button open Excel the first time but not on subsequent clicks?

This is typically caused by Excel's single-instance behaviour combined with a session-isolation fault. Verify that WinCC Runtime is running in the same interactive session as the operator console; if WinCC runs as Session 0 service, the first launch goes to the hidden session and subsequent calls are queued. Also confirm no WaitOnReturn = True argument is blocking the script thread.

How do I open an Excel file when the path is stored in a WinCC WString tag?

Use oShell.Run "EXCEL.EXE " & SmartTags("HMI_WString_Tag"), 1, False. The space between EXCEL.EXE and the variable is mandatory. If the path contains spaces, enclose it in escaped quotes: oShell.Run "EXCEL.EXE """ & SmartTags("HMI_WString_Tag") & """. Validate the tag value with Trim() and FileSystemObject.FileExists() before launching.

Which Office path do I use for Office 2016/2019/2021/365 on a 64-bit Windows host?

For MSI installs: C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE. For Click-to-Run installs (Microsoft 365 Apps): C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE. Always verify by right-clicking the Excel shortcut and selecting Open file location to confirm the actual install path on the runtime station.

Can I open Excel from a WinCC Unified Comfort Panel script?

No. Comfort Panels do not expose ProgramExecute or COM automation. Use the Open file client function configured under the button's Click event with the Program mode set to launch Excel with the file argument. The Siemens Industry Online Support portal documents the supported panel-side functions per firmware version.

My C action compiles but no Excel window appears. How do I diagnose?

First verify the path string in the compiled output: use sprintf(szBuf, "%s", lpProgram); and write to SetTagChar for visual inspection. Second, enable WinCC APDiag tracing on Graphics Runtime and look for CreateProcess failures. Third, capture a Sysinternals Process Monitor filtered on EXCEL.EXE; the trace shows whether CreateProcess is invoked and the returned NTSTATUS, pinpointing path, permission, or session issues.

Back to blog