Exporting WinCC Archive Tags to Excel: VBScript and CSV Guide

David Krause16 min read
HMI / SCADASiemensTutorial / How-to
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

Exporting WinCC Archive Tags to Excel: VBScript, C-Script, and CSV Methods

Siemens WinCC (TIA Portal and WinCC V7.x) provides multiple paths to generate Excel reports from archived tags. This technical reference covers three field-proven approaches: built-in CSV export from the Trend view, VBScript automation of Microsoft Excel, and C-Script logging with a downstream Excel wizard. Each method addresses different runtime versions, row-count ceilings, and reporting complexity levels encountered in process, batch, and SCADA deployments.

Scope: This guide applies to WinCC V6.2 SP2+, WinCC V7.0 SP3+, WinCC V7.2, WinCC V7.3, WinCC V7.4 SP1, WinCC V7.5, and the TIA Portal WinCC Professional / WinCC Runtime Advanced editions. Where behavior diverges between versions, the version is named explicitly.

1. Method Selection Matrix

Method WinCC Version Output Format Row Limit Custom Formatting External Excel Required
Trend view Save (CSV) WinCC V6.2+ / TIA WinCC RT CSV No hard cap (file system) No No (open in Excel after)
VBScript Excel automation WinCC V6.2+ / TIA WinCC RT XLS / XLSX Excel 2003: 65,536 rows; Excel 2007+: 1,048,576 rows Yes (full Excel object model) Yes (runtime / engineering station)
C-Script logging + Excel wizard WinCC V6.0+ CSV consumed by Excel VBA macro No hard cap (CSV) Yes (Excel-side macro) Yes (engineering / report station)
WinCC Reporting (TIA) / WinCC IndustrialDataBridge TIA WinCC Professional V14+ XLSX, PDF, CSV Configurable Yes (template-based) No (built-in connector)

2. Prerequisites

Before implementing any of the export methods, verify the following prerequisites on the WinCC runtime station and the report-generation station.

  1. WinCC runtime licensing: Archive tags require the optional "WinCC/Archives" or "WinCC Logging" license. The license key is located in the License Analyzer (Start » All Programs » Siemens Automation » WinCC » Tools » License Analyzer).
  2. Configured tag archive: Create or open the Tag Logging editor (WinCC Explorer » Tag Logging) and confirm that the process tags you want to report are inserted as archive tags with a defined acquisition cycle and archiving cycle. Without an archive tag, you are reporting on a live tag and risk losing data points between samples.
  3. Microsoft Excel installation: For VBScript automation, Microsoft Excel (2003, 2007, 2010, 2013, 2016, 2019, 2021, or 365) must be installed on the WinCC runtime station. The VBScript runtime uses the COM interface Excel.Application. Verify by running cscript //nologo "C:\Windows\System32\slmgr.vbs" /dli is not needed; instead check regedit » HKCR\Excel.Application for the COM registration.
  4. Filesystem rights: The WinCC runtime user (typically SYSTEM for services or the logged-in user for interactive runtime) must have read/write permission on the target export folder. A common path is C:\WinCC\Reports\.
  5. Template workbook: For VBScript automation, prepare a pre-formatted .xls or .xltx template with the desired header row, column widths, and cell formulas. Place the template in a known absolute path.
Important 64-bit caveat: WinCC V7.x runtime is 32-bit. Microsoft Excel installations on the same station may be 64-bit. The VBScript CreateObject("Excel.Application") call will fail with "ActiveX component can't create object" if bitness mismatches occur. Install 32-bit Microsoft Office on WinCC V7.x runtime stations, or switch to the in-process C-Script CSV approach.

3. Method A: Built-in CSV Export from the WinCC Trend View

The Trend view control in WinCC V6.2 and later exposes a Save toolbar button that writes the currently visible trend values to a CSV file. This is the lowest-effort approach and is ideal when the report dataset fits in memory and no template formatting is required.

3.1 Enable the Save Button

  1. Open Graphics Designer and select the Trend view object.
  2. In the Configuration dialog, navigate to Toolbar.
  3. Activate the "Save data" button. In TIA Portal WinCC Professional the property is Toolbar » ShowSaveButton = true.
  4. Under Operator control » Configuration of the data export, define the file path, filename pattern (for example, Trend_%date%_%time%.csv), and field separator (semicolon for German locales, comma for English).

3.2 Trigger the Export

At runtime, the operator selects the time range, clicks the Save icon, and confirms the dialog. The resulting file is a semicolon-delimited CSV ready for direct opening in Excel.

3.3 Verifying the Output

  1. Open the generated CSV in Microsoft Excel.
  2. Confirm that the first column contains the timestamp in DD.MM.YYYY HH:MM:SS format and the second column contains the tag value with decimal separator matching the configured locale.
  3. Verify that the row count matches the trend time range × acquisition cycle (for example, 24 h × 1 s = 86,400 rows).
Field limit: The Trend view Save button exports only the currently visible time window. For 24/7 scheduled reports, automate the call via a button script (Method B) or use the IndustrialDataBridge (Method D).

4. Method B: VBScript Excel Automation

The VBScript approach uses the Excel COM automation model to open a template, write tag values cell-by-cell, and save to a new file. This is the most flexible method and supports custom headers, formula-driven summaries, multiple sheets, and chart objects.

4.1 Reference: VBScript Tags for Archive Access

WinCC VBScript exposes archive tag values through the HMIRuntime.Tags collection. Two key methods are used:

  • HMIRuntime.Tags("TagName").Read — Returns the current live value. Use this for snapshot reports only.
  • HMIRuntime.Tags("TagName").Archive — Returns a Archive object whose Data method returns a SafeArray of archived values when invoked through the Tag Logging OCX (legacy WinCC V6.x). For TIA Portal WinCC, use the HMIRuntime.Logging object with GetLoggedValues / GetLoggedTagValuesList.

4.2 Sample VBScript: Export Live Tag Snapshot

The following script opens a pre-formatted template, writes a single value into a cell, saves to a new file, and cleanly releases the COM objects. Use this as a starting template for a daily report generation button on a WinCC screen.

' =====================================================================
' ExportToExcel.vbs - WinCC VBScript to export a live tag snapshot
' Target: WinCC V6.2 SP2+ / WinCC V7.x / TIA WinCC RT
' Place on: Button "Mouse click" event (left mouse button) in Graphics Designer
' =====================================================================

Dim objFSO, objExcel, objWorkbook, objWorksheet, objTag

On Error Resume Next

' --- 1. Create the Excel automation object ---
Set objExcel = CreateObject("Excel.Application")
If Err.Number <> 0 Then
    MsgBox "Excel.Application could not be created. Check that Microsoft Excel is installed.", vbCritical, "Export Error"
    Exit Sub
End If

objExcel.Application.DisplayAlerts = False   ' suppress "File exists" prompts
objExcel.Application.Visible = False        ' run in background

' --- 2. Open the template workbook ---
Const TEMPLATE_PATH = "C:\WinCC\Reports\template_daily.xls"
Const OUTPUT_PATH   = "C:\WinCC\Reports\report_" & Year(Now) & _
                       Right("0" & Month(Now), 2) & Right("0" & Day(Now), 2) & _
                       "_" & Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & ".xls"

Set objWorkbook = objExcel.Workbooks.Open(TEMPLATE_PATH)
If Err.Number <> 0 Then
    MsgBox "Template file not found: " & TEMPLATE_PATH, vbCritical, "Export Error"
    objExcel.Quit
    Set objExcel = Nothing
    Exit Sub
End If

Set objWorksheet = objWorkbook.Worksheets(1)

' --- 3. Read tag value (snapshot mode) ---
Set objTag = HMIRuntime.Tags("ProcessValue_Tank1")
objTag.Read

If objTag.LastError = 0 Then
    objWorksheet.Cells(1, 1).Value = Now                 ' A1: timestamp
    objWorksheet.Cells(1, 2).Value = objTag.Value        ' B1: tag value
    objWorksheet.Cells(1, 3).Value = objTag.QualityCode  ' C1: quality (0=Good)
Else
    objWorksheet.Cells(1, 1).Value = Now
    objWorksheet.Cells(1, 2).Value = "Error"
    objWorksheet.Cells(1, 3).Value = objTag.LastError
End If

' --- 4. Save the new workbook ---
objWorkbook.SaveAs OUTPUT_PATH, -4143   ' -4143 = xlNormal (.xls)
If Err.Number <> 0 Then
    MsgBox "SaveAs failed: " & Err.Description, vbCritical, "Export Error"
End If

' --- 5. Clean up COM objects (CRITICAL) ---
objWorkbook.Close False
objExcel.Application.DisplayAlerts = True
objExcel.Quit

Set objTag = Nothing
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
Object cleanup is mandatory. Excel.exe remains in memory for every VBScript call that does not nullify its objects. After 30 to 50 unattended runs, the WinCC runtime station will exhibit "COM exception" errors and out-of-memory conditions. Always assign Nothing to objExcel, objWorkbook, and objWorksheet at the end of the script.

4.3 Sample VBScript: Bulk Export from an Archive Tag

To dump an entire archive window into Excel, use the HMIRuntime.Logging object (TIA Portal) or the legacy OCX (WinCC V6.x / V7.x). The following script uses the TIA API to retrieve up to 10,000 logged values and writes them column-by-column into a worksheet.

' =====================================================================
' ExportArchiveToExcel.vbs - TIA Portal WinCC Professional
' Iterates through archive tag values between StartTime and EndTime
' =====================================================================

Dim objExcel, objWkb, objWks, objLog, objValList, objVal
Dim lngRow, strStart, strEnd, strOutput

strStart = "2026-01-15 00:00:00.000"
strEnd   = "2026-01-15 23:59:59.000"
strOutput = "C:\WinCC\Reports\archive_20260115.xlsx"

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
Set objWkb = objExcel.Workbooks.Add
Set objWks = objWkb.Worksheets(1)

objWks.Cells(1, 1).Value = "Timestamp"
objWks.Cells(1, 2).Value = "Value"
objWks.Cells(1, 3).Value = "Quality"

' --- Retrieve archive data ---
Set objLog = HMIRuntime.Logging
Set objValList = objLog.GetLoggedTagValuesList("ProcessValue_Archive", _
                                                CDate(strStart), _
                                                CDate(strEnd), _
                                                10000)

lngRow = 2
For Each objVal In objValList
    objWks.Cells(lngRow, 1).Value = objVal.Timestamp
    objWks.Cells(lngRow, 2).Value = objVal.Value
    objWks.Cells(lngRow, 3).Value = objVal.Quality
    lngRow = lngRow + 1
Next

objWks.Columns(1).NumberFormat = "dd.mm.yyyy hh:mm:ss"

objWkb.SaveAs strOutput, 51   ' xlOpenXMLWorkbook (.xlsx)
objWkb.Close False
objExcel.Quit

Set objVal = Nothing
Set objValList = Nothing
Set objLog = Nothing
Set objWks = Nothing
Set objWkb = Nothing
Set objExcel = Nothing

The exact method name and parameter set depends on the runtime version. In WinCC V7.x use the legacy approach:

' WinCC V7.x legacy OCX access (Tag Logging)
Dim objArchive, objData
Set objArchive = CreateObject("WinCC runtime object").GetObject("Tag Logging RT")
Set objData = objArchive.GetArchiveValueList("ProcessValue_Archive", _
                                              CDate(strStart), _
                                              CDate(strEnd))

Refer to the WinCC V7.5 Scripting Manual for the complete COM method reference: WinCC V7.5 Scripting: VBScript Reference.

5. Method C: C-Script with CSV Logger and Excel Wizard

When the report is large (over 65,000 rows) or Excel cannot be installed on the WinCC runtime, the recommended pattern is to log data in CSV from a C-Script and process the file with an Excel VBA macro on a separate engineering station.

5.1 C-Script: Append Tag Value to CSV

Place this C-Script on a scheduled trigger (e.g., 1-second cyclic action in Global Actions). The script opens the CSV in append mode, writes a timestamp + value, and closes the file handle to release the lock.

// =====================================================================
// LogToCSV.c - WinCC Global Action, cyclic trigger (1 s)
// Appends a timestamped value to C:\WinCC\Logs\ProcessValue_Archive.csv
// =====================================================================

#include "apdefap.h"
void Trigger_LogToCSV(char* lpszPictureName, char* lpszObjectName,
                       char* lpszPropertyName)
{
    FILE* fp;
    char  szTime[32];
    char  szDate[32];
    char  szLine[256];
    float fValue;

    fValue = GetTagFloat("ProcessValue_Archive");
    GetSystemTime(szTime, 32);
    GetSystemDate(szDate, 32);

    fp = fopen("C:\\WinCC\\Logs\\ProcessValue_Archive.csv", "a");
    if (fp == NULL) return;

    sprintf(szLine, "%s;%s;%.3f\r\n", szDate, szTime, fValue);
    fputs(szLine, fp);
    fclose(fp);
}

5.2 Excel VBA Macro: Build the Formatted Report

On a separate report station, run this VBA macro from the target workbook to consume the CSV and format it. The macro reads the raw file into a worksheet, applies formatting, computes summary statistics, and inserts a trend chart.

' Place in ThisWorkbook module of the report template
Sub BuildDailyReport()
    Dim wsRaw As Worksheet, wsReport As Worksheet
    Dim csvPath As String
    Dim i As Long, lastRow As Long
    
    csvPath = "C:\WinCC\Logs\ProcessValue_Archive.csv"
    
    ' --- 1. Load CSV ---
    Set wsRaw = ThisWorkbook.Sheets("RawData")
    With wsRaw.QueryTables.Add(Connection:="TEXT;" & csvPath, _
                                Destination:=wsRaw.Range("A1"))
        .TextFileParseType = xlDelimited
        .TextFileSemicolonDelimiter = True
        .Refresh BackgroundQuery:=False
        .Delete
    End With
    
    lastRow = wsRaw.Cells(wsRaw.Rows.Count, 1).End(xlUp).Row
    
    ' --- 2. Compute summary statistics ---
    Set wsReport = ThisWorkbook.Sheets("Report")
    wsReport.Range("B2").Value = "Min" : wsReport.Range("C2").Formula = "=MIN(RawData!C2:C" & lastRow & ")"
    wsReport.Range("B3").Value = "Max" : wsReport.Range("C3").Formula = "=MAX(RawData!C2:C" & lastRow & ")"
    wsReport.Range("B4").Value = "Avg" : wsReport.Range("C4").Formula = "=AVERAGE(RawData!C2:C" & lastRow & ")"
    
    ' --- 3. Insert chart ---
    Dim ch As ChartObject
    Set ch = wsReport.ChartObjects.Add(Left:=300, Top:=10, Width:=500, Height:=250)
    ch.Chart.SetSourceData Source:=wsRaw.Range("A2:C" & lastRow)
    ch.Chart.ChartType = xlLine
    
    ' --- 4. Save report ---
    ThisWorkbook.SaveAs "C:\WinCC\Reports\DailyReport_" & Format(Now, "yyyymmdd") & ".xlsx"
    MsgBox "Report generated. Rows processed: " & lastRow, vbInformation
End Sub

This separation of concerns is the industry-standard pattern for OT networks where the runtime station is air-gapped from the office IT network.

6. Method D: TIA Portal WinCC IndustrialDataBridge

For modern TIA Portal WinCC Professional V14+ deployments, the SIMATIC WinCC IndustrialDataBridge connector provides a fully graphical, schedule-driven data export. Configure a source (SQL Server archive) and a target (Excel file, CSV file, FTP, or OPC UA), then bind a trigger (time-based or event-based).

6.1 Quick Configuration Steps

  1. Open the TIA Portal project, add the IndustrialDataBridge plug-in.
  2. Create a Source: SQL Server, table ARCHIVE, columns TIMESTAMP, VALUE, QUALITY.
  3. Create a Target: Excel Single Sheet, output path C:\Reports\Daily.xlsx.
  4. Create a Mapping: bind source columns to target columns.
  5. Create a Trigger: Daily, 23:55:00.

7. Scheduled, Unattended Report Generation

To run a report at a specific time without operator interaction, use the WinCC Scheduler. In the WinCC Explorer, open Scheduler, create a new task, and bind it to a Global Action or VBScript. The task can be one-shot, daily, weekly, or monthly. Common configurations:

  • Daily production report: Trigger at 06:00, export previous 24 h of tags.
  • End-of-batch report: Trigger via tag event (Batch_Done = 1) with one-shot re-arm.
  • Weekly KPI rollup: Trigger Monday 00:00, aggregate 7-day window.

8. Performance and Capacity Considerations

Dataset Size Recommended Method Expected Runtime Memory Footprint
< 1,000 rows Method B (VBScript live) < 2 s Low
1,000 – 50,000 rows Method B (archive dump) 5 – 30 s Medium (Excel COM)
50,000 – 250,000 rows Method C (CSV + Excel macro) 10 – 60 s Medium (CSV) / High (Excel)
> 250,000 rows Method C with SQL Server staging 1 – 5 min High (SQL)
Excel 2003 row limit: 65,536 rows. The legacy VBScript code in Section 4.2 wrote to .xls format and will fail with "Cannot shift objects off sheet" when exceeded. Always check the dataset size in advance or default to .xlsx (Excel 2007+, 1,048,576 rows).

9. Troubleshooting Matrix

Symptom Likely Root Cause Resolution
"ActiveX component can't create object" on CreateObject("Excel.Application") Excel not installed, or bitness mismatch (32-bit WinCC / 64-bit Office) Install 32-bit Office on WinCC V7.x runtime stations, or switch to Method C
Excel.exe processes accumulate in Task Manager COM objects not released to Nothing Add explicit Set objExcel = Nothing at end of script and call objExcel.Quit
SaveAs fails with permission error WinCC runtime user lacks write permission to target folder Grant write permission to the runtime service account; use a folder under C:\WinCC\Reports\
Tag value is always 0 in the report objTag.Read not called, or Read returns Quality != 0 (Bad) Call objTag.Read first, then check objTag.QualityCode (0 = Good)
Archive returns empty SafeArray Tag not configured as archive tag, or archiving disabled Open Tag Logging editor and confirm the tag has a valid archive configuration and the Runtime archive manager is running
CSV opens with all data in column A Wrong regional separator (German OS uses ";", English uses ",") Match the field separator in the C-Script to the regional setting, or use Excel's Data » Text to Columns wizard
Trend Save button is greyed out Operator authorization level too low Open User Administration, assign the "Save data" right to the operator's level
Report file is locked, cannot be overwritten Previous Excel instance still holds handle Ensure DisplayAlerts = False and close workbook with .Close False (False = no save prompt)

10. Verification Procedure

After deploying any of the methods, run the following verification checklist on the runtime station and on the report consumer station.

  1. File creation check: Trigger the export script and confirm that the target file exists at the configured path. Verify the file size is greater than zero bytes.
  2. Header integrity: Open the file in Excel and confirm the first row contains the expected column headers exactly as defined in the template.
  3. Value fidelity: Compare a sampled value in the report to the live value displayed on the WinCC screen at the same timestamp. Tolerance should be within the tag's configured precision (typically ± 0.1% of span).
  4. Process leak check: Open Windows Task Manager and confirm that no residual Excel.exe process is left running after the script completes.
  5. Schedule check: For unattended reports, wait for the next scheduled trigger (or manually advance the Scheduler clock) and confirm the file is generated within the expected tolerance window.
  6. Empty-state behavior: Disable archiving for a test tag and trigger the report. Confirm the script handles the empty dataset gracefully (header-only file, log entry, or message box) rather than throwing a hard error.

11. Best Practices and Field-Proven Caveats

  • Never run Excel automation in a tight loop. A VBScript that exports 10,000 rows cell-by-cell is approximately 30 times slower than a bulk CopyFromRecordset from an ADO query against the SQL archive.
  • Use template files, not code-built workbooks. Generating sheets, borders, fonts, and charts from VBScript is brittle. Build a template in Excel with named ranges (e.g., ReportDate, AvgValue) and reference them via objWorksheet.Range("ReportDate").Value.
  • Localize the timestamp. Now returns the runtime station local time. If the report is consumed across time zones, format explicitly in UTC using FormatDateTime(Now, vbUniversalTime) and note the time zone in the cell comment.
  • Archive retention policy. Configure the Tag Logging archive to rotate (WinCC Explorer » Tag Logging » Properties » Archive Configuration » Segment size / Time range) so that long-running reports do not pull data from a corrupted or truncated archive.
  • Audit trail. Log the report filename, generation timestamp, and triggering user (or scheduler) to a status text file for 21 CFR Part 11 or similar regulatory environments.
Security note: VBScript in WinCC runs under the context of the runtime user, not the operator. Restrict the template and output folders via NTFS ACLs to prevent tampering. For higher-security deployments, use the IndustrialDataBridge with write-only destination credentials.

12. Frequently Asked Questions

How do I generate an Excel report from WinCC archive tags without installing Excel on the runtime station?

Use Method C: a C-Script appends timestamped values to a CSV file on the runtime station, and a separate engineering station runs an Excel VBA macro to consume the CSV and build a formatted report. This pattern works for datasets larger than the 65,536-row Excel 2003 limit and is the standard approach in air-gapped OT/IT networks.

Why does VBScript CreateObject("Excel.Application") fail on a 64-bit Windows installation?

WinCC V6.x and V7.x are 32-bit applications. If Microsoft Office installed on the same station is 64-bit, the COM object is registered under the 64-bit hive and is invisible to the 32-bit WinCC VBScript engine. The fix is to install 32-bit Microsoft Office on the WinCC runtime station, or move the Excel generation off the runtime station to a separate report generator.

What is the difference between HMIRuntime.Tags(...).Read and accessing archive data in VBScript?

Read returns only the current live process value. To export historical values, use the TIA Portal HMIRuntime.Logging.GetLoggedTagValuesList method or the WinCC V7.x legacy OCX GetArchiveValueList. These methods accept a start time, end time, and maximum row count and return a structured result you can iterate row by row.

Can the WinCC Trend view Save button be automated by a script?

Yes. In TIA Portal WinCC Professional, configure the Trend view with Toolbar.ShowSaveButton = true, then trigger the export via a VBScript that calls the corresponding method on the trend object. In legacy WinCC V6.x, use the ActiveX automation interface and invoke the Save action. For unattended scheduled reports, prefer the IndustrialDataBridge connector.

How can I find archived files in Excel that were generated by WinCC?

Open Microsoft Excel, press Ctrl + O, and navigate to the configured output folder (default C:\WinCC\Reports\). To find files generated on a specific date, use the search box with the file name pattern, e.g., report_20260115*. For Microsoft 365 users, archived (read-only) cloud copies can be located via the Data Archive extension in the Excel ribbon.

Back to blog