Auto-Exporting Daily WinCC Trend Data with VB Scripts

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

1. Problem Statement and Functional Overview

Engineers running WinCC Comfort/Advanced or WinCC Professional (TIA Portal) on a Panel PC, Comfort Panel, or RT PC frequently need to archive one or more process tags over a full 24-hour window (00:00:00 – 23:59:59) and export that archive automatically — without operator interaction. The native Online Trend Control does not include a built-in "daily export at 00:00" job. You must wire the time range, the trigger event, and the export call together manually, typically through VBScript or C script attached to a hidden I/O field that monitors a binary tag flipped by the PLC or by a WinCC scheduler.

This article documents the field-proven method used on TIA Portal V16 – V18 projects, including:

  • Time-range assignment to an OnlineTrendControl via the TrendWindow properties in VBScript.
  • Edge-triggered export using a binary tag that pulses once per day at 00:00.
  • Hidden I/O field event so the script runs in every screen, not just the trend screen.
  • Alternative paths via WinCC/DataMonitor Excel workbooks and Microsoft Power Automate for downstream distribution.

2. Prerequisites

Component Required Version / Setting
TIA Portal V16, V17, or V18 (WinCC Comfort/Advanced or Professional)
Runtime WinCC Runtime Advanced V16+ or WinCC Runtime Professional V16+
License WinCC RT Comfort/Advanced or RT Professional (the export API requires the full Runtime, not the demo)
Archive Tag logging configured with a "Cyclic" or "On demand" logging mode and a path on the local drive or network share
File system NTFS share with write permission for the HMI runtime user (commonly \<Server>\Reports$\WinCC\)
VBScript support Enabled in runtime settings (default on for Comfort/Advanced and Professional)
Optional: DataMonitor WinCC/DataMonitor V7.5+ or TIA Option "WinCC/DataMonitor" for Excel workbook export
Optional: Power BI Power BI Pro/Premium per user and a Power Automate premium connector license if exporting PBIX reports
All script paths in this article use the VBScript dialect of WinCC Runtime. C scripts (SCPAT) require a separate script project and are not interchangeable.

3. Architecture and Data Flow

The end-to-end daily export pipeline consists of five functional blocks:

  1. Trigger source — A Boolean (binary) tag in the PLC or the HMI that goes TRUE at 00:00:00 and resets shortly after. This can be a scheduler on the PLC, an HMI-side time event, or a Windows Task Scheduler action that writes a tag via OPC.
  2. Edge detector — A hidden I/O field bound to the trigger tag, polled every 1 s. The "OnChange" event fires the export script.
  3. Time-range setter — VBScript that writes TrendWindowStartTime and TrendWindowEndTime on the Online Trend Control using SmartTags and the system time.
  4. Export call — VBScript that calls the control method (or the archive's Export function) to write a CSV / TXT / XLSX to disk.
  5. Distribution — Optional downstream step: copy to a network share, push to SharePoint, or feed into Power BI through Power Automate.

3.1 Topology Diagram

The following inline SVG summarizes the runtime data flow:

PLC Scheduler / Time Task Binary Tag "mStopShift" Hidden I/O Field OnChange Event VBScript Export TrendWindow + Export CSV / XLSX file share

4. Configuring the Time Range in the Online Trend Control

Open the Online Trend Control in the HMI screen. On the Time axis tab, set the time range to "Configuration" mode so the range is set by VBScript, not the operator. The two properties of interest are:

Property Type Description
TimeAxisStartTime Date Beginning of the visible window
TimeAxisEndTime Date End of the visible window
TimeAxisRange Long Window length in seconds (used when Relative is selected)

When "Configuration" is selected, the runtime reads the values directly from the property node of the control, so VBScript can override them at any moment.

To assign today as the date and 00:00:00 / 23:59:59 as the start / end times, use this snippet inside a scheduled action or a button click event:

' ----------------------------------------------------------------
' ConfigureOnlineTrendWindow.vbs
' Sets the Online Trend Control "TrendView1" on screen "Screen_1"
' to display the current calendar day (00:00:00 - 23:59:59).
' ----------------------------------------------------------------
Dim dToday, dStart, dEnd, oScreen, oTrend

dToday = Date()            ' e.g. 2024-05-17
dStart = dToday & " 00:00:00"
dEnd   = dToday & " 23:59:59"

Set oScreen = HMIRuntime.Screens("Screen_1")
Set oTrend  = oScreen.ScreenItems("TrendView1")

oTrend.TimeAxisStartTime = dStart
oTrend.TimeAxisEndTime   = dEnd

' Optional: also force a redraw
oTrend.Activate = True
In WinCC Professional (TIA Portal), the screen-item path is identical. In older WinCC flexible 2008, the property names are TimeAxisBeginTime and TimeAxisEndTime.

5. Binary-Tag Trigger with Hidden I/O Field

The simplest, most reliable trigger is a Boolean tag that the PLC sets once per day. On the HMI, place a 1-bit I/O field on the root screen (or any screen that is always loaded) and bind it to the tag. Set the acquisition cycle to 1000 ms. Configure the field's Change event to call a VBScript function named TriggerDailyExport. The tag itself is reset by the script after a successful export, so a single edge fires only one event per day.

5.1 PLC-Side Trigger Example (S7-1500 SCL)

// S7-1500 SCL — daily pulse at 00:00:00
#triggerTag := FALSE;
IF (DT_TO_TOD(#dtNow) >= TOD#00:00:00) AND
   (DT_TO_TOD(#dtNow) <  TOD#00:00:05) AND
   NOT #edgeLatched THEN
    #triggerTag := TRUE;
    #edgeLatched := TRUE;
END_IF;
IF (DT_TO_TOD(#dtNow) >= TOD#00:00:05) THEN
    #edgeLatched := FALSE;
END_IF;

The output #triggerTag is wired to the HMI tag mStopShift shown in the original C-script snippet, ensuring the rising edge is captured even if the HMI poll cycle misses the 5-second window.

5.2 VBScript — Daily Export Procedure

' ----------------------------------------------------------------
' TriggerDailyExport()
' Edge-triggered by the hidden I/O field. Runs only when the
' binary tag transitions from 0 to 1. Performs the export, then
' clears the tag so a second edge can fire the next day.
' ----------------------------------------------------------------
Sub TriggerDailyExport()
    Dim oScreen, oTrend, dStart, dEnd, sPath, sFile

    If Not SmartTags("mStopShift") Then Exit Sub

    ' 1) Re-arm the time window for the day that just ended
    dStart = DateAdd("d", -1, Date()) & " 00:00:00"
    dEnd   = DateAdd("d", -1, Date()) & " 23:59:59"

    Set oScreen = HMIRuntime.Screens("Screen_1")
    Set oTrend  = oScreen.ScreenItems("TrendView1")

    oTrend.TimeAxisStartTime = dStart
    oTrend.TimeAxisEndTime   = dEnd

    ' 2) Build the destination file name
    sPath = "C:\Reports\WinCC\"
    sFile = sPath & "Daily_" & _
            Year(DateAdd("d",-1,Date())) & "-" & _
            Right("0" & Month(DateAdd("d",-1,Date())),2) & "-" & _
            Right("0" & Day(DateAdd("d",-1,Date())),2) & ".csv"

    ' 3) Export the visible trend to CSV using the
    '    Online Trend Control's built-in print/export action.
    '    "ExportCSV" invokes the CSV export dialog silently if the
    '    control is configured to suppress prompts.
    oTrend.ExportCSV sFile

    ' 4) Reset the trigger so the next edge is detected
    SmartTags("mStopShift") = False
End Sub
If ExportCSV is not available on your control (it is a method on the ProTool/WinCC flexible ActiveX control but not on every Runtime Advanced control), fall back to the generic HMIRuntime.Tags archive read using TagLogFileRead as shown in section 6.

6. C-Script Alternative (Compact Syntax)

For projects still maintained in C script, the same logic is shorter. The pattern published on the WinCC scripting reference uses the GetTagBit call inside an If block and an early Return for the negative case:

// C-script executed on the I/O field change event
if (GetTagBit("mStopShift") == 1)
{
    // Place export actions here
    // Example: archive export through internal functions or
    //          by calling a VBScript function via
    //          ProgramExecute("TriggerDailyExport");
}
return;

This matches the original example posted in the discussion thread: a one-line guard around the export body. C scripts cannot directly call every VBScript method, so for the actual export step, the usual pattern is to invoke a global VBScript function using ProgramExecute (WinCC V7.x) or to write the archive data to a tag buffer and let a screen-level VBScript do the file I/O.

7. The "Hidden Field" Pattern Explained

Placing the trigger script on a single trend screen means the export only fires when the operator happens to be on that screen at 00:00. To run the export regardless of which process screen is currently active, add the I/O field and its Change event to a permanent window or a screen that is loaded as a "global screen". In WinCC Comfort/Advanced, the equivalent is the Global Screen with a 1×1 invisible I/O field; in WinCC Professional, use a "Permanent window" on the root template.

Visibility is suppressed by:

  1. Setting the field's Position X/Y off-screen (e.g. -50,-50).
  2. Setting the layer to a layer that no other object uses, ensuring no other element overlaps it.
  3. Clearing the Label text.
  4. Setting Display → Visible off at runtime (in TIA Portal: property Visible bound to a constant Boolean FALSE).

The field is functionally invisible but its Change event still fires.

8. DataMonitor Excel Workbook Alternative

If your project already includes the WinCC/DataMonitor option, you can replace the manual VBScript export with a configured Excel workbook that pulls archive data via the DataMonitor web service. The drawback historically reported is that the time-controlled export feature in DataMonitor has not always worked reliably with the "nice reporting" wizard. Two workarounds keep this path viable:

  1. External trigger — Use a Windows scheduled task (see Microsoft Task Scheduler objects) that runs a VBScript which connects to the DataMonitor web service and triggers a report at 00:00.
  2. VBA macro workbook — Author the workbook to use Application.OnTime TimeValue("00:00:00"), "DailyExport" on workbook open, then keep the workbook always loaded on a session-host PC.

Neither approach is as clean as the VBScript method in sections 4–5, but both are valid fall-backs when the export API on the trend control is locked down by project policy.

9. Power BI / Power Automate Distribution Layer

Once the CSV lands on the network share, the next step is often to push it into a Power BI report and e-mail it to the operations team. The Power Automate export and e-mail flow documents the four supported trigger types:

Power Automate trigger Use case
Scheduled flow (recurrence) Daily 00:05 pull of the CSV written by WinCC, refresh the dataset, export the PBIX, send the file by e-mail
"When a file is created" (SharePoint / OneDrive) Push the CSV to a SharePoint library; the flow detects the new file and triggers the refresh
"When an item is created" (Dataverse) Insert a row into a Dataverse table from WinCC via OPC UA, then let Power Automate drive the report refresh
Manual button flow Operator-initiated on-demand re-export of the last 24 h

The recommended connector is the Power BI — Export and Send Report action, which accepts workspaceId, reportId, exportFormat (PDF, PPTX, PNG, XLSX), and an e-mail recipient. Power Automate will then call the Power BI REST API exports endpoint, poll until the export is ready, and attach the file to the e-mail.

10. Verification and Commissioning Procedure

  1. Start the runtime and navigate to the trend screen. Confirm the time axis shows today's 00:00 to 23:59 after running ConfigureOnlineTrendWindow.vbs manually from the script editor.
  2. Force the trigger tag from the PLC watch table. Confirm the hidden I/O field shows a red border in the layout (debug mode only) and the script fires.
  3. Inspect the destination share for the expected Daily_YYYY-MM-DD.csv file. Open it in Excel; columns should be Timestamp,TagValue,QualityCode.
  4. Set the PLC clock to 23:59:55 and wait for the rollover. Confirm a second file is produced for the day that just ended.
  5. Stop the runtime, re-start, and confirm that the trigger fires only once per day (no duplicates from the latching logic).
  6. Run the Power Automate flow manually. Verify the e-mail is received with the expected attachment.

11. Troubleshooting Matrix

Symptom Likely Cause Fix
Script never fires Hidden I/O field is not loaded (no global screen) Place field on a permanent window or global screen
Script fires twice Trigger tag is not reset Set mStopShift = False at the end of the script
Time window is wrong Time zone or DST mismatch between PLC and HMI Use UTC inside the script and convert at display time
Export file is empty Archive logging is configured "On change" with no activity during the day Switch to "Cyclic" logging or insert a dummy tag that always changes
Permission denied on share Runtime user has no write access Grant Modify permission to the service account running the WinCC RT
Method ExportCSV not found Control variant does not expose the method Use TagLogFileRead + manual FileSystemObject write
Power Automate flow fails with 401 Expired Power BI Pro token Re-authenticate the connector in Power Automate
Trend shows "No data" at 00:00 Time axis offset is not refreshed after writing the property Call oTrend.Activate = True after setting the time properties

12. Field-Proven Caveats

  • On a Panel PC running Windows IoT, the runtime user is SiemensUser by default. Network shares that authenticate against Active Directory require the same account or a domain trust.
  • The TimeAxisStartTime property expects a Date value, not a string. Passing "2024-05-17 00:00:00" as a string will be coerced by VBScript, but on systems with a non-US regional setting it can be parsed as MM-DD-YYYY. Use CDate to force ISO-8601 parsing.
  • If you also need to export alarms or audit trails, add a second hidden field bound to a similar trigger and a second script that calls HMIRuntime.AlarmLogging.Read.
  • When migrating a project from WinCC flexible 2008 to TIA Portal V17/V18, expect the property names to differ. Always verify with the auto-completion in the script editor rather than copying snippets verbatim.
  • For very long-running plants (multi-year archives), export the daily CSV and append it to a master Excel workbook via Power Query. Avoid keeping more than ~10 000 rows per file for responsive pivot tables.

How do I set the Online Trend Control time range to 00:00 – 23:59 of the current day in VBScript?

Bind the trend axis to "Configuration" mode in the screen editor, then assign oTrend.TimeAxisStartTime = Date() & " 00:00:00" and oTrend.TimeAxisEndTime = Date() & " 23:59:59" in VBScript. Call oTrend.Activate = True afterwards to force a redraw.

Why doesn't my export script run when the trend screen is not visible?

VBScript events on a control only fire while the host screen is loaded. Place the trigger I/O field on a permanent window or global screen so the event fires regardless of which process screen is active.

Can I trigger the export from the PLC instead of the HMI scheduler?

Yes. Set a Boolean tag in the PLC for 5 seconds at 00:00 and read it in a 1 s polled hidden I/O field on the HMI. The C-script snippet if (GetTagBit("mStopShift") == 1) { ... } is the most compact way to consume that edge.

What is the difference between the Online Trend Control export and the DataMonitor Excel export?

The Online Trend Control export is a one-off file write triggered by VBScript. The DataMonitor Excel export pulls data from the archive web service into a formatted workbook with charts. The first is simpler and license-free, the second produces richer reports but requires the DataMonitor option.

How do I send the exported CSV to operators by e-mail every morning?

Place the CSV on a OneDrive or SharePoint folder and create a Power Automate scheduled flow with the "Power BI — Export and Send Report" action (or the standard "Send e-mail" action with the file attachment). Trigger the flow at 00:05 to give the WinCC export time to complete.

What TIA Portal versions support the ExportCSV method on the trend control?

The method is available on WinCC Comfort/Advanced V14 SP1 and later, including V16, V17 and V18. On WinCC flexible 2008 the control exposes SaveData instead; the syntax differs and requires an absolute path argument.

Back to blog