WinCC Runtime Advanced V17: Stop Excel Temp Files Filling C Drive

David Krause14 min read
SiemensTroubleshootingWinCC
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

WinCC Runtime Advanced V17: Stop Excel Temp Files Filling C Drive

When a WinCC Runtime Advanced V17 panel PC runs a scheduled VBScript that opens Excel via CreateObject("Excel.Application"), the C: drive can fill with Excel lock files, PDF spool fragments, and COM working copies within an hour. The temp files are not produced by WinCC Runtime itself; they are a side effect of the Excel COM (Component Object Model) automation. This reference walks through diagnosing the leak, hardening the script, and reconfiguring the runtime so the panel boots clean every shift.

Scope: TIA Portal V17 project, WinCC Runtime Advanced V17, MS Office automation in scheduled VBScripts. Applies to Panel PC, SIMATIC IPC, and PC-based WinCC RT Advanced installations that publish PDF/XLSX reports.

1. Problem Description

Operators report that the C: drive on the panel PC runs out of free space within one to two hours of starting WinCC Runtime Advanced V17. Tree C:\ /F /A shows thousands of files in:

  • C:\Users\<RuntimeUser>\AppData\Local\Temp — Excel/Office working files, OLE compound documents, MSO cache files
  • C:\Users\<RuntimeUser>\AppData\Roaming\Microsoft\Excel — recent file list, add-in caches
  • C:\Windows\Temp — print spool fragments from ExportAsFixedFormat
  • The same folder as the destination XLSX — ~$REPORT ROOM D1_*.xlsx Office lock files

WinCC Runtime itself logs to its configured log database (Tag Logging / Alarm Logging) but does not create text log files in C:\ by default. The temp file storm only starts when a VBScript calls CreateObject("Excel.Application") and the VBScript runtime tries to write to disk via the Excel COM process.

2. How WinCC Runtime Advanced V17 Executes VBScripts

WinCC Runtime Advanced V17 hosts the Microsoft VBScript engine in-process. When a VBScript (a function, a scheduled action, or a tag-triggered action) calls CreateObject("Excel.Application"), the WinCC process asks the Windows Service Control Manager to launch a separate EXCEL.EXE process and bind to it through COM. Each invocation that fails to release the COM reference keeps the EXCEL.EXE process alive; the visible Excel.exe instances accumulate.

Object Model Host Process Temp File Locations Used Cleanup Trigger
HmiRuntime.SmartTags, HmiRuntime.Tags, HmiRuntime.Screens WinCCRTAdv.exe (in-process) Project log paths, configured log DB Configured retention in Tag/Alarm Logging
CreateObject("Excel.Application") EXCEL.EXE (out-of-process COM server) %LOCALAPPDATA%\Temp, %APPDATA%\Microsoft\Excel, destination folder (lock files), %WINDIR%\Temp (print spool) Workbook.Close + Excel.Quit + Set objExcelApp = Nothing + GC
CreateObject("Scripting.FileSystemObject") WinCCRTAdv.exe User-defined paths only User-defined

The mixed in-process / out-of-process model is the root of the leak. WinCC Runtime can release its own objects deterministically, but the Excel COM server has its own crash-recovery and lock-file logic that WinCC cannot override.

3. Why Excel COM Automation Floods C:\ With Temp Files

Every call sequence below creates a file that survives the script unless the script explicitly removes it:

Operation File Created Default Path Size Order
Workbooks.Open(url) ~$<filename>.xlsx Same folder as the workbook ~ 1–8 KB
Workbook.Save / SaveAs ~XXXX.tmp OLE compound doc %LOCALAPPDATA%\Temp 4 KB – 4 MB
ActiveSheet.ExportAsFixedFormat 0, url, ... Print spool fragment, MSO cache %WINDIR%\Temp, %LOCALAPPDATA%\Temp\Microsoft\Windows\INetCache 0.5 – 30 MB per page
Workbook.Close without Set = Nothing Orphaned EXCEL.EXE process, retained lock file — —

A typical report script that runs every minute generates 60 such cycles per hour. With three sheets, three PDF pages, and the default Excel recovery cache, the system produces 200–500 MB/h of orphaned *.tmp and ~$ files. Over an 8-hour shift, that exceeds the free space on a 30 GB panel partition.

Field observation: On SIMATIC IPC227G with a 64 GB SSD, the C: partition is typically carved to 30–40 GB for the Windows image. A single 5-sheet PDF report every 60 seconds fills the partition in 60–90 minutes if Excel.Quit is skipped or fails due to an unhandled COM error swallowed by On Error Resume Next.

4. Identifying the Real Source of the Files

  1. Open an elevated PowerShell prompt and capture disk usage: Get-ChildItem C:\ -Recurse -ErrorAction SilentlyContinue | Group-Object Extension | Sort-Object Count -Descending | Select-Object -First 20.
  2. List the largest temp files: Get-ChildItem $env:TEMP, $env:LOCALAPPDATA\Temp, C:\Windows\Temp -Recurse -ErrorAction SilentlyContinue | Sort-Object Length -Descending | Select-Object -First 20 FullName, Length.
  3. Inspect the names: ~$*.xlsx indicates Excel lock files; ~DF*.tmp, ~WR*.tmp, or random GUID names indicate Word/Excel print-spool and OLE cache.
  4. Cross-check against running processes: Get-Process | Where-Object {$_.ProcessName -match "Excel|WinCC"} | Select Name, Id, StartTime, @{N="Handles";E={$_.HandleCount}}. A rising EXCEL.EXE count while the script is on a one-minute schedule confirms a COM lifecycle leak.
  5. Open WinCC RT Advanced with the diagnostic log level: in TIA Portal V17, set the runtime start parameter /diagnostics via the HMI device's "Runtime settings > Startup" parameters and capture WinCCRTAdv.log in the project log directory.

If the only files accumulating are Excel-related, the leak is in the VBScript. If you also see *.log or *.ldf files filling the project directory, jump to Section 8 (native logging retention).

5. Root Cause: Excel.Application Object Lifecycle

The VBScript pattern in the failing project uses On Error Resume Next as the first line of the procedure. This swallows COM errors that Excel raises when Workbook.Save collides with an existing lock file, when the print spool cannot be written, or when Workbook.Close is invoked while the user (or a stale COM reference) holds the file. The error is suppressed, the cleanup lines are skipped, and the orphaned EXCEL.EXE plus its ~$ files accumulate.

There are four interacting defects in the original script:

  1. No error-handler granularity. On Error Resume Next is procedure-wide, so any failure in CreateObject, Workbooks.Open, Save, ExportAsFixedFormat, or Quit is masked and the cleanup branch is never taken.
  2. No finalization block. VBScript does not have try/finally; the only way to guarantee objWorkbook.Close, objExcelApp.Quit, and Set objExcelApp = Nothing run is to wrap them in a dedicated cleanup subroutine and call it from every exit point.
  3. Template file copy races. The template is copied with FileSystemObject.CopyFile immediately before Workbooks.Open. If the previous run's lock file still exists, the copy or open fails silently and the lock file is orphaned.
  4. No temp-directory redirection. Excel uses the system temp path of the account that launched it. By default that is the WinCC Runtime service account's %LOCALAPPDATA%\Temp on C:.

6. Fix 1: Harden the VBScript (Object Lifecycle and Workbook Hygiene)

Rewrite the script to release the COM objects in a controlled cleanup path. The pattern below uses a per-step error handler, a single exit point, and a forced workbook-close flag.

' ROOM_D1_REPORT - hardened for WinCC RT Advanced V17
' Scheduled action: every 60 s, report destination: D:\REPORT\ROOM_D1_REPORT
Option Explicit

Sub ROOM_D1_REPORT()
    Dim strDate, strTime
    Dim url_Folder, url_File, url_FileRef, url_Filepdf
    Dim objFSO, objExcelApp, objWorkbook
    Dim Row_HeaderPos, Row_Actual, Row_DataWrite, tempVal
    Dim bOpenedExcel : bOpenedExcel = False
    Dim bOpenedBook  : bOpenedBook  = False
    Dim iErrNum, sErrDesc
    On Error Goto CleanFail   ' use a real handler, not Resume Next

    strDate = DatePart("yyyy", Date) & "_" & Right("0" & DatePart("m", Date), 2) & "_" & Right("0" & DatePart("d", Date), 2)
    strTime = Right("0" & Hour(Now), 2) & "h_" & Right("0" & Minute(Now), 2) & "m_" & Right("0" & Second(Now), 2)
    url_Folder  = "D:\REPORT\ROOM_D1_REPORT\" & strDate
    url_File    = url_Folder & "\REPORT ROOM D1_" & strDate & ".xlsx"
    url_FileRef = "D:\REPORT_REF_FILE\ROOM_D1_REPORT.xlsx"
    url_Filepdf = url_Folder & "\REPORT ROOM D1_" & strDate & ".pdf"

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If Not objFSO.FolderExists(url_Folder) Then objFSO.CreateFolder(url_Folder)

    ' --- Remove stale lock file from a prior aborted run -----------------
    If objFSO.FileExists(url_File) Then
        On Error Resume Next
        objFSO.DeleteFile url_File, True
        On Error Goto CleanFail
    End If

    objFSO.CopyFile url_FileRef, url_File, True
    Set objFSO = Nothing

    ' --- Open Excel out-of-process ----------------------------------------
    Set objExcelApp = CreateObject("Excel.Application")
    bOpenedExcel = True
    objExcelApp.Visible        = False
    objExcelApp.ScreenUpdating = False
    objExcelApp.DisplayAlerts  = False
    objExcelApp.AskToUpdate    = False
    objExcelApp.Calculation    = -4135     ' xlCalculationManual

    Set objWorkbook = objExcelApp.Workbooks.Open(url_File, False, False)
    bOpenedBook = True

    Row_HeaderPos = 7
    With objWorkbook.ActiveSheet
        Row_Actual    = .Cells(.Rows.Count, "A").End(-4162).Row
        Row_DataWrite = Row_Actual + 1
        .Cells(Row_DataWrite, "A") = Now
        tempVal = Round(HmiRuntime.SmartTags("ROOM-4 DISPLAY TEMP FL"), 2)
        .Cells(Row_DataWrite, "B") = tempVal
        .Cells(Row_DataWrite, "B").NumberFormat = "0.00"
    End With

    objWorkbook.Save
    objWorkbook.ActiveSheet.ExportAsFixedFormat 0, url_Filepdf, 0, 1, 0
    bOpenedBook = False
    objWorkbook.Close False
    Set objWorkbook = Nothing
    bOpenedExcel = False
    objExcelApp.Quit
    Set objExcelApp = Nothing
    Exit Sub

CleanFail:
    iErrNum  = Err.Number
    sErrDesc = Err.Description
    HmiRuntime.Trace "ROOM_D1_REPORT error 0x" & Hex(iErrNum) & ": " & sErrDesc
    If bOpenedBook  Then On Error Resume Next : objWorkbook.Close False : On Error Goto 0
    If bOpenedExcel Then On Error Resume Next : objExcelApp.Quit     : On Error Goto 0
    Set objWorkbook = Nothing
    Set objExcelApp = Nothing
    Err.Raise iErrNum, , sErrDesc
End Sub

Key changes:

  • Replace On Error Resume Next with On Error Goto CleanFail; keep the per-step fallback for the DeleteFile call only.
  • Pre-delete the destination workbook (which also drops any ~$ lock file from a prior crashed run).
  • Disable Excel calculation, alerts, and the Office update prompt to keep the COM surface quiet.
  • Track opened state with boolean flags so the cleanup branch always closes what was opened.
  • Force objWorkbook and objExcelApp to Nothing so the WinCC VBScript host releases its references before the next tick.

7. Fix 2: Redirect Excel and Print-Spool Temp Directories

Even with the hardened script, Excel still writes print-spool fragments during ExportAsFixedFormat. Move Excel's working path off C: by setting the relevant environment variables for the user that runs WinCC Runtime.

Variable Value (recommended) Effect
TEMP / TMP D:\Runtime\Temp Used by all Win32 applications including Excel.
LOCALAPPDATA D:\Runtime\LocalAppData (and create the standard subfolders: Microsoft\Excel, Microsoft\Windows\INetCache, ...) Excel stores OLE compound documents and the recovery cache here.
APPDATA D:\Runtime\AppData Excel add-in and ribbon caches.
Excel "AutoRecover" path (File > Options > Save) D:\Runtime\Temp\AutoRecover Disables the C: default auto-recover directory.

Apply via System Properties > Environment Variables for the user that starts WinCCRTAdv.exe, or via a startup script:

setx TEMP         "D:\Runtime\Temp"          /M
setx TMP          "D:\Runtime\Temp"          /M
setx LOCALAPPDATA "D:\Runtime\LocalAppData"  /M
setx APPDATA      "D:\Runtime\AppData"       /M

Then create the canonical subdirectories on D: so Office does not recreate them on C: at first launch:

mkdir D:\Runtime\Temp
mkdir D:\Runtime\LocalAppData\Microsoft\Excel\XLSTART
mkdir D:\Runtime\LocalAppData\Microsoft\Windows\INetCache
mkdir D:\Runtime\AppData\Microsoft\Excel
Service-account caveat: If WinCC Runtime starts as a Windows service, environment variables set with setx /M are picked up only on next logon of that service account. Restart the Runtime service or reboot the panel after the change. Do not change %WINDIR% paths directly; Excel always falls back to %WINDIR%\Temp if its primary temp path is unwritable.

8. Fix 3: Replace Excel Automation With Native WinCC Logging

For per-minute data logs, the native WinCC Tag Logging is the supported, disk-safe mechanism. The custom VBScript in Section 6 should be considered transitional. Tag Logging stores values directly in a configured database (Microsoft SQL Server Express bundled with WinCC RT Advanced, or a CSV ring buffer), with configurable retention. No COM server is launched, so no temp files are created.

Approach Disk Footprint Excel/PDF Export Recommended Use
Tag Logging (SQL Express) Ring-buffer controlled; < 200 MB/year for 1 tag/min Export to CSV/XLSX via ExportTagLogging or control-center action Production of per-shift trend reports
Tag Logging (CSV, file-based) Configurable segment size, e.g. 50 MB rotated Same export as SQL Panel PCs without SQL Express
VBScript + Excel COM 200–500 MB/h (uncontrolled) → 0 after hardening Direct XLSX/PDF output Only when the report layout must include formulas, charts, or formatting not reproducible in Tag Logging

To migrate the VBScript's data row to Tag Logging:

  1. In TIA Portal V17, open the HMI device > "Tag Logging" > "Data logs" and add a new log named RoomD1_Log.
  2. Add the tag ROOM-4 DISPLAY TEMP FL with a 60 s acquisition cycle. Add a "Logging cycle" of 60 s.
  3. In the "Runtime settings > Services" tab, configure the log path to D:\Runtime\Logs\TagLogging and the retention to "Delete segments older than 30 days" or "Maximum 50 segments".
  4. Use the function ExportTagLogging from a scheduled action at the end of shift to write a CSV or XLSX to D:\REPORT\ROOM_D1_REPORT\ using the Open XML SDK, not Excel COM.

For PDF output without Excel, the WinCC function PrintReport (or the "Reports" area in the project) prints a configured report to a PDF printer such as "Microsoft Print to PDF" or a network PDF printer; this no longer uses Excel COM and is the long-term fix.

9. Fix 4: Scheduled Temp-File Cleanup

Add a defensive cleanup that runs every 15 minutes and removes orphans older than 30 minutes (Excel always finishes its writes within seconds, so anything older is leaked). The script is invoked by a WinCC scheduled action that uses Shell.Application or a PowerShell call, but PowerShell is preferred because it can be signed with a Siemens-approved code-signing certificate.

# Cleanup-TempFiles.ps1 - run by WinCC scheduled action or Task Scheduler
$paths = @(
    "$env:TEMP",
    "$env:LOCALAPPDATA\Temp",
    "$env:LOCALAPPDATA\Microsoft\Windows\INetCache",
    "C:\Windows\Temp"
)
$cutoff = (Get-Date).AddMinutes(-30)
Get-ChildItem -Path $paths -Recurse -Force -ErrorAction SilentlyContinue |
    Where-Object {
        $_.LastWriteTime -lt $cutoff -and
        ($_.Name -like '~$*' -or $_.Name -like '~DF*' -or $_.Name -like '~WR*' -or
         $_.Extension -in '.tmp')
    } |
    Remove-Item -Force -ErrorAction SilentlyContinue

Trigger from WinCC Runtime Advanced with a scheduled action of period 900000 ms (15 min) that runs the function RunCleanup defined in a global module. The function uses WshShell.Run "powershell -NoProfile -ExecutionPolicy Bypass -File D:\Runtime\Scripts\Cleanup-TempFiles.ps1", 0, True. Do not set True to False; you want the cleanup to finish before the next tick.

10. Firmware and Software Compatibility: Update WinCC Runtime Advanced V17

Several Excel COM lifecycle issues in V17 are addressed in subsequent updates. After any fresh installation of WinCC Runtime Advanced V17, install the latest available update; the published list of fixes and prerequisites is the authoritative reference.

The V20 readme clarifies that only the matching WinCC Runtime version can be started from the Engineering System; other versions can only be simulated. This matters when you troubleshoot with a TIA Portal V17 ES installed next to a V18/V19 panel image — the runtime that consumes the project must match the project's ES, and a mismatch can route COM calls into the wrong Office library, exacerbating the temp-file leak.

Compatibility note: Microsoft Office 2016, 2019, 2021, and Microsoft 365 Apps all expose the same Excel.Application ProgID, but their temp-file behavior differs. Pin a single Office build on the panel and lock it with sfc /scannow and a Group Policy that prevents Office Click-to-Run updates from changing the binary mid-shift. The supported Microsoft Office versions for WinCC RT Advanced V17 are listed in the TIA Portal V17 installation manual; verify against that document before deploying.

11. Verification and Commissioning Checklist

  1. Capture baseline disk usage: (Get-PSDrive C).Free.
  2. Start WinCC Runtime Advanced with the hardened script and the PowerShell cleanup task enabled.
  3. Run the schedule for 8 hours (one full shift). The Free value at the end should be within ±2% of the baseline.
  4. Verify that no EXCEL.EXE instance remains after the script completes: (Get-Process Excel -ErrorAction SilentlyContinue).Count must be 0 within 5 s of the schedule tick.
  5. Verify the destination folder: only the requested REPORT ROOM D1_YYYY_MM_DD.xlsx and the matching .pdf exist; no ~$ file is present.
  6. Verify the temp paths: Get-ChildItem D:\Runtime\Temp, D:\Runtime\LocalAppData\Temp -Recurse | Measure-Object Length -Sum; total should be < 200 MB after 8 hours.
  7. Verify Tag Logging (if migrated): open the configured log file with the WinCC information server, confirm that the data row at minute boundaries is present and that segments rotate at the configured size.
  8. Verify error trace: HmiRuntime.Trace lines in WinCCRTAdv.log for ROOM_D1_REPORT error 0x... must be zero for a clean 8-hour run.

12. Troubleshooting Matrix

Symptom Most Likely Cause Diagnostic Fix Reference
~$<file>.xlsx in destination folder Workbook.Close not reached due to error Search WinCCRTAdv.log for 0x800... trace Section 6 (harden script)
~DF*.tmp or ~WR*.tmp in %WINDIR%\Temp ExportAsFixedFormat print-spool leak Count files per schedule tick Section 7 (redirect temp) + Section 9 (cleanup)
EXCEL.EXE count grows linearly objExcelApp.Quit never reached Get-Process | Sort StartTime Section 6
C: full within 60 min, no Excel files Project log directory on C:, retention too high Check Tag/Alarm Logging retention Section 8
Cleanup script fails with "access denied" EXCEL.EXE still holds the file Get-Process Excel Section 6 cleanup + wait-then-delete in Section 9
Project does not compile in V17 after script change On Error Goto not in first non-comment line Compile in TIA Portal V17 Section 6: ensure On Error Goto CleanFail is the first executable line
HmiRuntime.SmartTags returns 0 every cycle Tag name has changed in TIA Portal V17 project Cross-check tag list Section 6: align tag name with current project
PDF is corrupted / 0-byte Print spool path unwritable Check ACL on redirected temp Section 7 (subfolder ACLs)

Frequently Asked Questions

Does WinCC Runtime Advanced V17 create its own temp log files on C: by default?

No. WinCC RT Advanced V17 writes only to the project log directory you configure (typically D:\...). Temp files on C:\Users\<user>\AppData\Local\Temp or C:\Windows\Temp are created by the COM servers your VBScript invokes — in almost all cases, Microsoft Excel.

How do I keep EXCEL.EXE from accumulating in Task Manager?

Open Excel with CreateObject("Excel.Application"), set Visible=False, DisplayAlerts=False, Calculation=-4135, save and close the workbook, then call objExcelApp.Quit and Set objExcelApp = Nothing in a single cleanup block. See the script in Section 6 of this article.

Where do I move Excel's temp files to keep them off C:?

Set the environment variables TEMP, TMP, LOCALAPPDATA, and APPDATA to D:\Runtime\... for the account that starts WinCCRTAdv.exe, then create the canonical Microsoft subfolders under the new paths. Restart the runtime service so the new variables are inherited.

Should I install every V17 update for WinCC Runtime Advanced?

Yes. Per Siemens Support ID 109800912, after each installation of WinCC Runtime Advanced V17 the latest update must be installed; this resolves several Excel COM lifecycle regressions that have been reported against the V17 base release.

Can I produce a PDF report without using Excel at all?

Yes. Use the WinCC "Reports" designer to create a report layout bound to Tag Logging, then call PrintReport from a scheduled action with a "Microsoft Print to PDF" or network PDF printer as the output device. This is the long-term replacement for the Excel-based PDF flow and does not launch EXCEL.EXE.

Back to blog