Delete XLS Files Using VBScript in Siemens WinCC HMI Runtime

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

Delete XLS Files Using VBScript in Siemens WinCC HMI Runtime

Overview

Siemens WinCC Runtime environments (WinCC Flexible 2008, WinCC Comfort/Advanced in TIA Portal V13 through V19) execute VBScript inside the HMI panel's runtime, where standard Windows file APIs are not directly available. To delete generated .xls, .csv, or .txt files from a panel's storage card, the script must use either the Siemens-supplied FileCtl.Filesystem COM object (the supported runtime API) or the standard Scripting.FileSystemObject (available on PC-based WinCC Runtime only). This reference shows the working pattern, the correct path conventions for a Siemens TP/Comfort Panel storage card, and the error-handling block required for production deployment.

The procedure below is engineered for a weld-results use case where the panel writes a series of .xls reports to \Storage Card SD\Weld_Results\ and a cleanup routine must purge the directory after data is archived. The same pattern applies to recipe exports, alarm logs, batch reports, and audit trails.

Runtime environment matters. The FileCtl.Filesystem object is exposed by the WinCC Runtime (RT) on a Siemens panel. Scripting.FileSystemObject only works when the script is executed on a Windows-based PC runtime (WinCC Runtime Advanced on a PC) because the panel's Windows CE / Win32 RT image does not include the full Windows Script Host COM stack on every firmware version. Match the object to the target device, or the script will fail with error 429 (ActiveX component can't create object).

Prerequisites

  1. WinCC project configuration: TIA Portal V13 SP1 or later (V16/V17/V18/V19 recommended for current firmware), with a Comfort Panel (TP700/TP900/TP1200/TP1500/TP1900) or a WinCC Runtime Advanced PC target.
  2. Storage medium: An SD card or USB stick formatted as FAT32, mounted on the panel. Internal flash and the \Storage Card SD\ path require the media to be present at boot.
  3. Runtime scripting enabled: In TIA Portal, open the HMI device → Properties → Runtime settings → Services. Enable VB scripting and confirm the script DLLs are deployed.
  4. User rights: The user logged in on the panel must have permission to write to the target directory. Configure the user administration under → "User administration" with at least Operator rights for the storage card path.
  5. Tag list: The SmartTags referenced in the cleanup script must be defined as HMI tags of the correct data type (Word, Int, Bool) before the script is executed.

WinCC VBScript File System Objects

Two COM objects are available for file-system work in WinCC Runtime VBScript. They are not interchangeable, and selecting the wrong one is the most common cause of the "Object doesn't support this property or method" runtime alarm on a panel.

Property FileCtl.Filesystem Scripting.FileSystemObject
Provided by Siemens WinCC Runtime Microsoft Script Runtime (scrrun.dll)
Available on Comfort Panel Yes (panel RT) No on most firmware versions
Available on WinCC Runtime Advanced (PC) Yes Yes
Methods used for delete Kill (wildcard), Dir (enumerate) DeleteFile, DeleteFolder
Enumeration method fs.Dir(path, [attr]) returns filename string Folder.Files collection, or Folder.Files.Count
Path format Backslash, no drive letter on CE: \Storage Card SD\Folder\ Full Windows path: C:\Folder\
Wildcard support in Kill Yes (*.*, *.xls) Yes (DeleteFile("*.xls"))
Read-only file handling Error 70 (Permission denied) Error 70 (Permission denied)

Microsoft VBScript Reference

The Delete method example (VBScript) on Microsoft Learn documents the canonical FileSystemObject.DeleteFile call against a hard-coded path. The pattern is identical to what is used inside WinCC PC Runtime:

Dim fso, FileToDelete
Set fso = CreateObject("Scripting.FileSystemObject")
FileToDelete = "c:\asdflkasd.xls"
fso.DeleteFile(FileToDelete)

On a Siemens panel this exact pattern returns error 429 because scrrun.dll is not registered in the panel runtime image. Use FileCtl on panels and Scripting.FileSystemObject on PC Runtime targets.

Path Conventions for Siemens Panels

The path string passed to FileCtl must follow the storage-card convention used by the panel's Windows CE / Windows Embedded Compact runtime:

Media WinCC path constant Sample target
Internal flash (CFC) \Storage Card CF\ \Storage Card CF\Weld_Results\file.xls
SD card \Storage Card SD\ \Storage Card SD\Weld_Results\file.xls
USB stick (front) \Storage Card USB\ \Storage Card USB\Weld_Results\file.xls
Network path \\server\share\ \\plc-archive\reports\*.xls
Use double backslashes in the VBScript string literal. VBScript treats \ as an escape, so the source code "\Storage Card SD\Weld_Results\file.xls" resolves at runtime to the device path \Storage Card SD\Weld_Results\file.xls. A single backslash yields an invalid path and triggers error 76 (Path not found).

Step-by-Step: Building the Delete Routine

Step 1 - Define the HMI tag interface

Create the SmartTags that the cleanup script will read and reset. All tags are HMI tags of type Word unless noted.

SmartTag Type Purpose
WR_fileCount Word Number of files present before deletion
WR_Files_present Bool Set TRUE when at least one file existed
WR_Linecount Word Row pointer for the on-screen table
WR_Total_pages Word Total pages in the file list
WR_Page_counter Word Current page index
WR_Page_Current Word Displayed page index
WR_Screen_arrow_dn_visible Bool UI scroll-down arrow visibility
WR_Screen_arrow_up_visible Bool UI scroll-up arrow visibility
WR_File_present Bool Flag for active file in table row
WR_Zero_ed Bool Flag for "editable" zero state

Step 2 - Build the enumeration phase

The first FileCtl.Filesystem instance is used to walk the directory with Dir. Each call returns the next matching filename; the loop continues until an empty string is returned.

Dim fs, cleanPath, file, strTemp, total, f, strTemp1, fso

'--- Enumeration: count files in target directory ---
Set fs = CreateObject("FileCtl.Filesystem")
SmartTags("WR_fileCount") = 0

strTemp = fs.Dir("\Storage Card SD\Weld_Results\" & "*.*")
While (Len(strTemp) > 0)
    SmartTags("WR_fileCount") = SmartTags("WR_fileCount") + 1
    strTemp = fs.Dir()    'no argument returns the next file
Wend

Step 3 - Execute the delete phase

A second FileCtl.Filesystem instance is created to call Kill with a wildcard. Reusing the same object after Dir resets its internal cursor; using two instances is cleaner and avoids the subtle "file 1 deleted but file 2 is the one I started with" off-by-one bug seen in field deployments.

Set fs = Nothing
Set fso = CreateObject("FileCtl.Filesystem")

strTemp1 = fso.Dir("\Storage Card SD\Weld_Results\*.*", 0)
fso.Kill("\Storage Card SD\Weld_Results\*.*")

Step 4 - Handle runtime errors

Kill raises VBScript errors that must be caught with On Error Resume Next and a manual Err.Number check. The WinCC function ShowSystemAlarm queues the message into the panel's alarm buffer for display in the alarm view.

If Err.Number <> 0 Then
    ShowSystemAlarm "Error#" & CStr(Err.Number) & " " & Err.Description
    Err.Clear
    Exit Sub
End If

Step 5 - Reset tag pointers and repaint the screen

After deletion, the on-screen table is stale. Reset the index tags and call the helper WR_Screen_Zero_Clear to repaint the table with zero rows.

SmartTags("WR_Files_present") = 0
SmartTags("WR_Linecount") = 0
SmartTags("WR_Total_pages") = 1
SmartTags("WR_Page_counter") = 1
SmartTags("WR_Page_Current") = 1
SmartTags("WR_Screen_arrow_dn_visible") = 0
SmartTags("WR_Screen_arrow_up_visible") = 0
SmartTags("WR_File_present") = 0
SmartTags("WR_Zero_ed") = 0

WR_Screen_Zero_Clear

If Err.Number <> 0 Then
    ShowSystemAlarm "Error#" & CStr(Err.Number) & " " & Err.Description
    Err.Clear
End If

Complete Working Script

Assemble the steps into a single subroutine and bind it to a button's "Click" event in the WinCC screen layout.

Sub WR_Delete_Files()
    On Error Resume Next
    Dim fs, cleanPath, file, strTemp, total, f, strTemp1, fso

    '--- Enumerate and count ---
    Set fs = CreateObject("FileCtl.Filesystem")
    SmartTags("WR_fileCount") = 0
    strTemp = fs.Dir("\Storage Card SD\Weld_Results\" & "*.*")
    While (Len(strTemp) > 0)
        SmartTags("WR_fileCount") = SmartTags("WR_fileCount") + 1
        strTemp = fs.Dir()
    Wend
    Set fs = Nothing

    '--- Delete all files in folder ---
    Set fso = CreateObject("FileCtl.Filesystem")
    strTemp1 = fso.Dir("\Storage Card SD\Weld_Results\*.*", 0)
    fso.Kill("\Storage Card SD\Weld_Results\*.*")

    If Err.Number <> 0 Then
        ShowSystemAlarm "Error#" & CStr(Err.Number) & " " & Err.Description
        Err.Clear
        Exit Sub
    End If

    '--- Reset pointers ---
    SmartTags("WR_Files_present") = 0
    SmartTags("WR_Linecount") = 0
    SmartTags("WR_Total_pages") = 1
    SmartTags("WR_Page_counter") = 1
    SmartTags("WR_Page_Current") = 1
    SmartTags("WR_Screen_arrow_dn_visible") = 0
    SmartTags("WR_Screen_arrow_up_visible") = 0
    SmartTags("WR_File_present") = 0
    SmartTags("WR_Zero_ed") = 0

    '--- Repaint table ---
    WR_Screen_Zero_Clear

    If Err.Number <> 0 Then
        ShowSystemAlarm "Error#" & CStr(Err.Number) & " " & Err.Description
        Err.Clear
    End If
End Sub

Verification Procedure

  1. Compile check: In TIA Portal, compile the HMI project. Any syntax error in the VBScript raises a red entry under → "Scripts" with the offending line.
  2. Simulator run: Start WinCC Runtime Advanced simulator, populate \Storage Card SD\Weld_Results\ with one or more .xls files, click the button bound to WR_Delete_Files. Confirm the files are removed and WR_fileCount drops to zero.
  3. On-panel run: Transfer the compiled project to the panel, repeat the test with a real SD card. Confirm the storage card is still readable in Windows after the panel is rebooted.
  4. Empty-folder run: Trigger the routine on an empty directory. Expect zero files enumerated, zero errors, and WR_fileCount = 0.
  5. Error path: Mark one .xls read-only on the SD card from a PC, lock the SD card write-protect tab, or remove the SD card before the script runs. The error branch must fire ShowSystemAlarm with the correct VBScript error number.

Error Codes and Diagnostics

Err.Number Description Likely cause Fix
52 Bad file name or number Single backslash, missing escaped \ Use \Storage Card SD\ literal
53 File not found Folder missing or wildcard mismatch Verify the directory exists with fs.Dir first
70 Permission denied File is read-only or locked open by Excel Close Excel automation, clear the read-only attribute
76 Path not found Typo, storage card not mounted Re-seat the SD card, check \Storage Card SD\
429 ActiveX cannot create object Scripting.FileSystemObject on a CE panel Switch to FileCtl.Filesystem
1001 FileCtl internal error File held open by another process Retry after closing the holding application

Troubleshooting Matrix

Symptom Root cause Resolution
Script does nothing on click Button event not bound Open the button → Events → Click → select WR_Delete_Files
Error 429 on a Comfort Panel Wrong COM object used Replace Scripting.FileSystemObject with FileCtl.Filesystem
Only some files deleted Kill called from a reused FileCtl object still iterating Use a fresh FileCtl.Filesystem instance for Kill after enumeration
Files reappear after reboot SD card is write-protected or corrupt Replace card, reformat as FAT32 with 32 KB cluster
Alarm shows "Path not found" on production panel but works in simulator Simulator runs on PC, panel uses CE path Hard-code the panel's exact \Storage Card SD\ path; do not reuse a PC test path
Script deletes a file the operator still needs Wildcard *.* too broad Change wildcard to *.xls or WR_*.xls
On Error Resume Next swallows a real fault Missing Err.Number check after each call Insert If Err.Number <> 0 Then Exit Sub after every FileCtl call

Safety and Operational Notes

Always validate the file list before deletion. Show the operator the count in WR_fileCount and require a confirmation button or an HMI password prompt before the Kill executes. The cleanup routine is destructive; an accidental trigger can wipe a day of weld results.

For audit-traceable systems, write a log line to a separate .csv file in \Storage Card SD\Audit\ before calling Kill:

fso.WriteLine "DELETE," & Now() & "," & SmartTags("WR_fileCount") & " files"

This same write can be performed with FileCtl.OpenTextFile on a panel runtime, mirroring the standard VBScript OpenTextFile / WriteLine pattern.

Cross-Platform Variant: PC Runtime (WinCC Runtime Advanced)

When the target is a Windows-based WinCC Runtime Advanced (PC station), switch to the standard Scripting.FileSystemObject to gain access to DeleteFile with attribute control, FSO folder enumeration, and Unicode paths.

Sub PC_Delete_Results()
    On Error Resume Next
    Dim fso, folder, files, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder("C:\Weld_Results")
    Set files = folder.Files
    For Each file In files
        If LCase(fso.GetExtensionName(file.Name)) = "xls" Then
            file.Delete True   'force delete even if read-only
        End If
    Next
    If Err.Number <> 0 Then
        ShowSystemAlarm "Error#" & CStr(Err.Number) & " " & Err.Description
        Err.Clear
    End If
    Set fso = Nothing
End Sub

The True argument to file.Delete forces removal of read-only files, which is not available from the panel-side FileCtl.Kill. Use this variant on PC Runtime only.

FAQ

Why does my WinCC VBScript fail with error 429 on a Comfort Panel?

Error 429 (ActiveX cannot create object) means the script is requesting Scripting.FileSystemObject on a Windows CE / Win32 panel runtime where scrrun.dll is not registered. Use the Siemens-supplied FileCtl.Filesystem COM object and call Kill("path\*.*") for deletion.

What is the correct path to the SD card in a WinCC panel script?

Use the literal \Storage Card SD\ prefix with double backslashes inside the VBScript string. Example: "\Storage Card SD\Weld_Results\*.xls". Single backslashes produce error 52 (Bad file name).

Can I delete only the .xls files and leave the .csv files?

Yes. Replace the wildcard *.* with the target extension, for example "\Storage Card SD\Weld_Results\*.xls". FileCtl.Kill accepts standard Windows wildcards, and Dir in enumeration uses the same pattern.

How do I avoid deleting files that another process has open?

Close any application holding the file (Excel, a file viewer, an FTP server streaming the report), then run the cleanup. If the panel itself has the file open in a viewer screen, switch to a different screen before triggering the delete. FileCtl.Kill returns error 70 (Permission denied) when the file is locked.

Does the same script work in TIA Portal V18 and V19 projects?

Yes. The FileCtl.Filesystem object and VBScript runtime are unchanged across WinCC Comfort/Advanced from TIA Portal V13 SP1 through V19. Code that compiles in V13 also compiles in V19, provided the SmartTag names and HMI tag definitions are ported with the project.

Back to blog