Building a WinCC OLE-DB Tag Logging Export Application in VBS

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

The legacy WinCC OLE-DB Tag and Alarm Export Excel workbook exposes a macro-based front end that connects to the runtime tag logging archive and pulls historical samples for a user-defined time window. Engineers migrating to WinCC V7.3 / V7.5 or to TIA Portal WinCC Professional frequently request a self-contained runtime application that performs the same query without requiring Excel. This reference documents how to translate the VBA routines of the original Excel add-in into a VBScript that runs inside the WinCC runtime, talks to the archive through the WinCC OLE-DB Provider, and writes the result set to a CSV file.

The procedure below is based on the official Siemens application example Entry ID 38132261 (WinCC V7.3 Export Example) and the FAQ Entry ID 35840700 – Export of WinCC / CAS Archive Data using the WinCC OLE DB Provider. The same VBS pattern applies to TIA Portal WinCC Professional V16 and later; the only differences are the project tree structure and the handling of the connection string for the TIA Runtime archive.

Architecture: How the WinCC OLE-DB Provider Exposes Archives

The WinCC runtime writes tag logging values to a proprietary database. Three access layers are available:

Access Layer Provider / Library Use Case Available In
WinCC OLE-DB Provider WinCCOLEDBProvider.1 (in-process OLE DB) Direct SQL against archive database from VBS, C#, VBA WinCC V7.0 SP2 and later, TIA WinCC Professional V14+
WinCC CAS Archive Provider WinCC-Archive-Provider (ADO.NET) .NET applications, WPF, custom SCADA add-ins WinCC V7.0 SP2 and later
WinCC User Archives UA-API (C / COM) Recipe / batch data (not process values) WinCC V7.0 and later

The OLE-DB provider is the only one that can be driven from VBScript with no additional installation, which makes it the path of least resistance for a screen-button-driven export. The provider registers a virtual database called CC_TLG_<N> for each configured tag logging cycle (where <N> is the archive number, 1-based). Each virtual database contains two tables:

  • TLG_<archive> – the user archive values
  • TLG_<archive>_<process_tagname> – a typed, indexed view per process tag

The connection string is a standard OLE DB connection string built with the WinCC OLE-DB enumerator:

Provider=WinCCOLEDBProvider.1; Catalog=CC_TLG_1; Data Source=<ServerName>\WinCC
Important: The Data Source segment must match the SQL server instance that hosts the WinCC archive database. On a single-station project the value is typically .<InstanceName> or localhost\WinCC. For a redundant pair, point to the virtual server name defined in the WinCC redundancy configuration.

Prerequisites

  1. WinCC V7.3 / V7.4 / V7.5 (Engineering + Runtime) or TIA Portal V16+ with WinCC Professional.
  2. License for the tag logging component (Runtime Tag Logging is part of the basic WinCC RT license, Alarm Logging is a separate RC license).
  3. Microsoft OLE DB Driver / SQL Server Native Client present on the runtime station. The WinCC OLE-DB provider depends on the SQL Server stack that ships with the WinCC installation.
  4. A configured Tag Logging cycle with at least one process tag (for example, a 1-second acquisition stored in a 1-day segment with a 30-day swap time).
  5. User rights to the WinCC project directory and to a target export path on the runtime station. The script writes the CSV to a directory that must exist; if the path is missing the runtime will fail silently or raise error 800A0046 (Permission denied) / 800A003A (File not found).
  6. Microsoft Script Debugger is optional; recommended for first-time deployment. It is not shipped with WinCC V7.4 SP1 or later and must be side-loaded from a pre-existing Windows installation or from the Visual Studio remote debugger.

Step 1 – Create the Project Skeleton

Open the WinCC Explorer (V7) or the TIA Portal project and add a new picture window that will host the export button. Add the following screen objects:

Object Name Purpose
I/O field edStartTime Beginning of time range (string, format YYYY-MM-DD HH:MM:SS)
I/O field edEndTime End of time range
I/O field edTagName Process tag name to query (must match archive view name)
Button btnExport Triggers the VBS action
Status display stResult Connected to an internal tag showing row count / error

Create an internal tag @ExportStatus (Text tag, length 80) to surface the result of the action to the operator.

Step 2 – The VBS Action Behind the Button

Open the mouse-click event of btnExport and add the following VBScript. The script mirrors the logic embedded in the original OLE-DB Tag Export Excel macro but is self-contained inside the WinCC picture.

'--- begin btnExport_Click -------------------------------------- Option Explicit Dim sConn, oConn, oRS, sSQL Dim sStart, sEnd, sTag, sFile Dim fso, ts, i, sLine, sVal sStart = SmartTags("edStartTime") SmartTags("edStartTime") = sStart 'normalise the input format SmartTags("edEndTime") = SmartTags("edEndTime") sStart = SmartTags("edStartTime") ' --- assemble SQL --------------------------------------------------- ' The view TLG_1_<TagName> exposes columns: Timestamp(UTC), RealValue, Quality ' Convert the local WinCC timestamp string into OLE-DB 'datetime' ' literal form: 'YYYY-MM-DD HH:MM:SS.000' sSQL = "SELECT Timestamp, RealValue, Quality " & _ "FROM TLG_1_" & sTag & " " & _ "WHERE Timestamp >= '" & sStart & "' " & _ "AND Timestamp <= '" & sEnd & "' " & _ "ORDER BY Timestamp ASC" ' --- build the connection ------------------------------------------ sConn = "Provider=WinCCOLEDBProvider.1;Catalog=CC_TLG_1;Data Source=.<WinCC>" Set oConn = CreateObject("ADODB.Connection") oConn.ConnectionString = sConn oConn.CursorLocation = 3 ' adUseClient oConn.Open Set oRS = CreateObject("ADODB.Recordset") oRS.ActiveCommand = CreateObject("ADODB.Command") Set sFile = "C:\WinCC_Export\" & sTag & "_" & _ Replace(sStart," ","_") & "_" & _ Replace(sEnd," ","_") & ".csv" Set fso = CreateObject("Scripting.FileSystemObject") If Not fso.FolderExists("C:\WinCC_Export") Then fso.CreateFolder "C:\WinCC_Export" End If Set ts = fso.CreateTextFile(sFile, True, False) ' ASCII, not Unicode oRS.Open sSQL, oConn, 3, 1 ' adOpenStatic, adLockReadOnly ' CSV header ts.WriteLine "Timestamp;RealValue;Quality(0=Good,1=Bad,2=Substituted)" Do While Not oRS.EOF sLine = oRS.Fields(0).Value & ";" & _ CStr(oRS.Fields(1).Value) & ";" & _ CStr(oRS.Fields(2).Value) ts.WriteLine sLine i = i + 1 oRS.MoveNext Loop ts.Close oRS.Close oConn.Close Set ts = Nothing Set oRS = Nothing Set oConn = Nothing Set fso = Nothing SmartTags("@ExportStatus") = "Exported " & i & " rows to " & sFile '--- end btnExport_Click ----------------------------------------

The script follows the same query structure that the Excel macro generates: SELECT Timestamp, RealValue, Quality FROM TLG_<archive>_<tagname> WHERE Timestamp BETWEEN .... The connection string is the same form used in the official FAQ Entry ID 35840700.

Catalog name: WinCC V7 creates one catalog per configured tag logging cycle, e.g. CC_TLG_1, CC_TLG_2. If you query a tag from cycle 2 you must change both the Catalog= parameter and the table name prefix TLG_2_. TIA Portal WinCC Professional uses the same naming convention starting with V14.

Step 3 – Mapping the WinCC Timestamp Format

WinCC returns timestamps as local-time strings in the YYYY-MM-DD HH:MM:SS form when read through the OLE-DB provider. The provider stores all values in UTC internally, but the column projection is converted to the runtime station's time zone. Two consequences follow:

  1. The WHERE clause must use the local time string the user typed, not a UTC conversion.
  2. If the WinCC station uses a different time zone than the operator's I/O field, an offset must be applied. Wrap the time string in a DateAdd("h", <offset>, ...) call before concatenating it into the SQL.

For daylight-saving handling, always query a window that does not span a DST switch and verify the result count against an external tool such as the WinCC Tag Logging editor before commissioning the runtime.

Step 4 – Handling Binary and String Tags

The view TLG_1_<tagname> for a non-numeric process tag exposes a different value column:

Process Tag Type Value Column SQL CAST
Real / Float / Double RealValue none
Integer / 16-bit / 32-bit RealValue none (returned as a numeric string)
Boolean / Bit RealValue 0 / 1 only
Text (8 / 16) RealValue (typed as text variant) wrap with CAST(RealValue AS VARCHAR(255))
Raw data type (DT / DTL) RealValue use CONVERT(VARCHAR(30), RealValue, 120)

For text tags, replace the column list in the SELECT to SELECT Timestamp, CAST(RealValue AS VARCHAR(255)) AS RealValue, Quality. The OLE-DB provider will accept the cast because the underlying archive is a SQL Server-compatible engine.

Step 5 – Error Handling and Diagnostic Codes

Wrap the connection and the recordset operations in a top-level On Error Resume Next and inspect Err.Number / Err.Description to surface problems to the operator. The most common failure modes for a WinCC OLE-DB export script are:

Symptom Err.Number Likely Root Cause Action
Provider cannot be found 0x800A0E7A WinCCOLEDBProvider.1 not registered on the runtime station Reinstall the WinCC Runtime, or register the DLL with regsvr32
Invalid authorization specification 0x80040E4D SQL Server not in mixed mode, or WinCC user not granted db_datareader on the archive Check WinCC User Administrator; the runtime user must own the archive
Empty result set, but data exists in Tag Logging editor none (silent failure) Catalog number does not match the cycle that owns the tag Verify CC_TLG_<N> index in the WinCC Explorer
Script aborts at ts.WriteLine 0x800A0046 CSV path does not exist or is read-only Pre-create the folder; never write to C:\ root if UAC is on
Garbled timestamps in the CSV none Regional setting mismatch between script locale and SQL Server collation Use the unambiguous YYYY-MM-DD HH:MM:SS.000 literal form
On Error Resume Next must be removed for production: the snippet above uses it for readability. In a deployed runtime, replace it with a structured error handler that logs to the WinCC diagnostics file <ProjectName>_RT.log via HMIRuntime.Trace.

Step 6 – Verifying the Export

  1. Compile and save the picture in the Graphics Designer. Activate the runtime.
  2. Open the export screen. Enter a time range of five minutes for a fast-cycling tag such as a 1-second acquisition.
  3. Click Export Tags. The status field must display Exported N rows to <path>\<tagname>_...csv.
  4. Open the CSV in Excel using Data → From Text/CSV with semicolon separator. The first row must read Timestamp;RealValue;Quality(...).
  5. Cross-check the row count against the WinCC Tag Logging editor (right-click the tag → Display archive data → select the same range). Counts must match within ±1 (boundary timestamps may differ by one row).
  6. Open the WinCC diagnostics window (Ctrl+D in the runtime). Confirm no entry OLE DB Provider error was logged.

Step 7 – Performance Considerations

The WinCC OLE-DB provider streams rows from the archive; memory consumption is dominated by the ADODB recordset buffer. For large time windows (days to weeks) at 1-second acquisition, follow these rules:

  • Set oConn.CursorLocation = 3 (adUseClient) so the client receives the full set in one shot. Switch to adUseServer (default 2) only for ad-hoc paginated queries.
  • For ranges above 250 000 rows, use CommandTimeout = 0 to disable the default 30-second command timeout.
  • Disable WinCC picture caching on the export screen so the action always runs against the live archive rather than a cached picture (set Display → Properties → Other → Cache picture = No).
  • Run the export in a background thread (VBS WSCript.Shell + a sibling VBS file) for windows larger than 1 million rows; the GUI thread must stay responsive to keep the HMI alive.
  • If the query is repeated (trend overlay, scheduled reports), store the SQL in an internal string tag and have the script only swap the time range. The query plan cache on the OLE-DB provider is per-connection; reusing the same statement shape yields significant speed-up after the first call.

Step 8 – Adapting the Script to TIA Portal WinCC Professional

The TIA Portal runtime exposes the same OLE-DB provider; only the project plumbing differs:

  1. Place the VBScript as a Scheduled task or as a button action in an HMI screen, exactly as in V7. TIA Portal stores scripts in the project tree under HMI → Screens → <Screen> → Events.
  2. The runtime archive database in TIA WinCC Professional is still named CC_TLG_<N> starting with V14, but the SQL Server instance name is typically .\WinCC for single-station and the redundancy virtual name for paired stations.
  3. For TIA WinCC Unified (V17+), the OLE-DB provider is not available. Switch to the WinCC Unified Archive Provider (REST) or the new Logging tag API. The script must be re-implemented in JavaScript.
  4. Refer to the official application example Entry ID 38132261 for the complete V7.3 sample project; the same project structure ports to TIA WinCC Professional with no source changes other than the catalog number.

Step 9 – Field-Commissioning Checklist

Check Method Pass Criterion
Connection string valid Use udl test file with the same string Test connection succeeds
Tag exists in archive WinCC Tag Logging editor → Display archive data At least one row visible
Time zone alignment Compare runtime station time with SQL Server SELECT GETDATE() Equal to the minute
Folder writable Open Notepad, save a file in the export directory Save succeeds without UAC prompt
CSV opens in Excel Double-click the file Opens with semicolons separating columns
Row count matches archive Compare COUNT(*) in the archive editor Equal or off-by-one at boundaries
Alarm Logging analog Run the script against a message archive view MS_<archive> Same pattern returns alarm rows
Long-range query Export 30 days × 1 s acquisition Completes in < 60 s on a single-station runtime

Step 10 – Extending the Script for Alarm Archives

The same technique works for the alarm logging archive. The OLE-DB catalog is CC_ALG_<N> and the table is MS_<N>. The columns returned are MsgNr, State, TimeStamp, Ms for state changes and acknowledgements. Substitute the connection string and the SELECT clause with the alarm form:

sConn = "Provider=WinCCOLEDBProvider.1;Catalog=CC_ALG_1;Data Source=.<WinCC>" sSQL = "SELECT MsgNr, State, TimeStamp, Ms " & _ "FROM MS_1 " & _ "WHERE TimeStamp >= '" & sStart & "' " & _ "AND TimeStamp <= '" & sEnd & "' " & _ "ORDER BY TimeStamp ASC"

The state code mapping for WinCC alarm archives is:

State Code Meaning
1 Came in (raised)
2 Went out (cleared)
3 Acknowledged
4 Status tag update

Step 11 – Known Limitations of the WinCC OLE-DB Provider

  • The provider is a 32-bit component. The VBScript runtime inside WinCC Graphics Designer is also 32-bit. External scripts that consume the archive from a 64-bit application (PowerShell x64, .NET Framework 4.x AnyCPU on x64 OS) must target x86 explicitly.
  • The provider does not support JOIN across tag logging and alarm logging catalogs. The two catalogs are separate SQL Server databases internally.
  • The provider cannot write to the archive. The connection is read-only. For backfill scenarios use the WinCC User Archives API instead.
  • Compressed archives must be decompressed by the runtime before the query can read them. Configure the archive's Archive Backup setting to Not compressed if the runtime must read historical segments older than the swap time.
  • The maximum length of a tag name that the OLE-DB provider accepts is 24 characters; the column names TLG_1_<name> will be truncated to the configured SQL Server identifier limit (128 by default).

Step 12 – Troubleshooting Matrix

Observed Behaviour First Verification Second Verification Final Fix
Empty CSV, status reports 0 rows Check that the time range falls within the configured archive time Open WinCC Tag Logging editor and confirm rows exist Adjust CC_TLG_N catalog number
Script does not fire Confirm button event is configured for Mouse-Click, not Mouse-Down Check that the picture is the active runtime window Set Events → Press → VBS Action
Timestamps off by one hour Inspect Windows Time Zone on the runtime station Check DST setting in WinCC computer properties Set Computer → Properties → Time zone = Use local time
CSV contains only the header row Verify the FROM clause points to TLG_N_<TagName> Use the OLE-DB browser in the WinCC Explorer to list tables Re-name the view in the tag logging configuration
Excel cannot read the file Open with Notepad; check whether commas or semicolons are used Confirm the regional list separator matches the script's separator Replace ; with Chr(59) in the script

Step 13 – Best Practices for Production Deployment

  1. Move the SQL template and the connection string into internal tags of type String so that operators can change the export directory or the catalog number at runtime without a redeploy.
  2. Log every export action to a WinCC alarm message of class System with the operator's username and the row count. This creates an audit trail for ISO 27001-style export controls.
  3. Use a scheduled VBS task (WinCC V7) or a TIA WinCC Professional Scheduler to run the export automatically at midnight, so that the operator does not have to press the button for compliance reports.
  4. Wrap the connection object in a class module (C++ / C# ATL) if the export script grows beyond 200 lines. VBScript does not support early binding to custom classes, so the wrapper must be a COM visible .NET assembly registered with regasm.
  5. For very large archives, replace the OLE-DB provider with a direct SQL Server view. The WinCC archive schema is documented in the WinCC Information Server manual and the underlying tables are accessible with the same credentials.

Which catalog number do I use for a tag that lives in tag logging cycle 3?

Use Catalog=CC_TLG_3 in the connection string and prefix the table name with TLG_3_. The catalog index is 1-based and matches the order in the WinCC Explorer under Tag Logging → [Cycle name].

How do I export text tags without losing characters?

Cast the RealValue column to a wide character type in the SELECT clause: SELECT Timestamp, CAST(RealValue AS NVARCHAR(255)) AS RealValue, Quality. The OLE-DB provider supports CAST and CONVERT against the archive engine.

Why does the script work in the Graphics Designer but not in the runtime?

The runtime runs as a service under the SYSTEM account, which has no network share access by default. Switch the runtime service to a domain user with read access to the SQL Server archive, or use a local folder for the export path. The WinCC OLE-DB provider cannot authenticate using Kerberos delegation unless the service is started with a domain user.

Can I write the export directly to a network share?

Yes, but map the share in the user context of the runtime service. A UNC path such as \\server\share\WinCC\ works as long as the service account has write permission and the share is reachable from the runtime station. The script does not need to know the path is a share; the FileSystemObject resolves it transparently.

Is the same script usable on TIA WinCC Unified?

No. WinCC Unified (V17 and later) removed the OLE-DB provider. Use the WinCC Unified Archive Provider (REST) or the Logging tags JavaScript API. The VBS-based script in this article targets WinCC V7 and TIA WinCC Professional (V14–V16) only.

Back to blog