WinCC VBScript 05 Days
Handwritten Code Manual

Notebook-style practical training pattern for WinCC Explorer / WinCC 7.x VBScript, SmartTags, SQL Server ADODB, alarm logging, recipe handling and trend reporting.

05 Days / 40 Lab Hours
M-Step Practical Notes
Code Examples Included
Mobile + Print Friendly

Notebook Pattern
VBScript + SQL
SCADA Manual

✓ SmartTags → ADODB → SQL → Alarm → Recipe → Trend

SOFTWELL VBSCRIPT
01PLC to PLC Communication Using VBScript 02Internal Tag Logging to SQL Server 03External PLC Tag Logging to SQL Server 04Conditional Logic IF / ELSE Writing to SQL 05Alarms, Recipes and Trends via VBScript
DAY 01

Softwell WinCC VBScript — Handwritten M-Step Manual

PLC to PLC Communication Using VBScript

Practical Outcome: Read WinCC source tags, validate values, write destination PLC tags and prepare a reusable transfer script.

SmartTagsPLC_01 to PLC_02Cyclic ScriptValidationTransfer Status
Trainer Note: First create tags and screen objects, then paste VBScript code in correct button action / cyclic action. Always test in Runtime and verify SQL result.
01
Step 1. Create WinCC tag groups PLC_01, PLC_02 and SYS inside Tag Management.
02
Step 2. Create source tags PLC1_TankLevel, PLC1_Pressure, PLC1_Temperature and PLC1_MotorCmd.
03
Step 3. Create destination tags PLC2_TankLevel, PLC2_Pressure, PLC2_Temperature and PLC2_MotorCmd.
04
Step 4. Create SYS_LastTransferStatus and SYS_LastTransferTime for operator feedback.
05
Step 5. Write basic SmartTags read/write script for manual transfer button.
06
Step 6. Use array-based loop to copy multiple tags from PLC_01 to PLC_02.
07
Step 7. Add IsNumeric and range validation before writing destination tags.
08
Step 8. Add SYS_TransferEnable bit for enabling/disabling automatic transfer.
09
Step 9. Test good value, bad value and communication-failure conditions in Runtime.
10
Step 10. Daily assignment: submit screenshot of source tags, destination tags, script and Runtime result.
VBScript Example 1Day 01
'Basic read/write pattern using SmartTags
Dim level
level = SmartTags("PLC1_TankLevel")
SmartTags("PLC2_TankLevel_SP") = level
VBScript Example 2Day 01
'Button action: CopyPLC1ToPLC2
Dim tags(3)
tags(0) = "TankLevel" : tags(1) = "Pressure"
tags(2) = "Temperature" : tags(3) = "MotorCmd"
Dim i
For i = 0 To 3
  SmartTags("PLC2_" & tags(i)) = SmartTags("PLC1_" & tags(i))
Next
SmartTags("SYS_LastTransferStatus") = "TRANSFER OK"
SmartTags("SYS_LastTransferTime")   = Now()
VBScript Example 3Day 01
Dim srcLevel, srcPressure
srcLevel    = SmartTags("PLC1_TankLevel")
srcPressure = SmartTags("PLC1_Pressure")

If IsNumeric(srcLevel) And srcLevel >= 0 And srcLevel <= 100 Then
  If IsNumeric(srcPressure) And srcPressure >= 0 And srcPressure <= 10 Then
    SmartTags("PLC2_TankLevel")  = srcLevel
    SmartTags("PLC2_Pressure")   = srcPressure
    SmartTags("SYS_LastTransferStatus") = "OK"
  Else
    SmartTags("SYS_LastTransferStatus") = "ERR: PRESSURE OUT OF RANGE"
  End If
Else
  SmartTags("SYS_LastTransferStatus") = "ERR: INVALID LEVEL"
End If
SmartTags("SYS_LastTransferTime") = Now()
Runtime Check: After Day 01, verify tag values, DB status tag, SQL rows and screenshots before moving to next day.

Daily Practice / Viva

Explain code line-by-line, show Runtime working screen, SQL query result and one troubleshooting point for Day 01.

DAY 02

Softwell WinCC VBScript — Handwritten M-Step Manual

Internal Tag Logging to SQL Server

Practical Outcome: Create Softwell_DB table and log WinCC internal tags into SQL Server using ADODB VBScript.

SQL ServerADODBInternal TagsINSERT QueryDB Status
Trainer Note: First create tags and screen objects, then paste VBScript code in correct button action / cyclic action. Always test in Runtime and verify SQL result.
01
Step 1. Create database Softwell_DB in SQL Server Management Studio.
02
Step 2. Create InternalTagLog table with Id, LogTime, BatchNo, SetPoint, ActualValue, OperatorName and ShiftName.
03
Step 3. Create internal tags INT_BatchNo, INT_SetPoint, INT_ActualValue, INT_OperatorName and INT_ShiftName.
04
Step 4. Design WinCC screen with I/O fields for all internal tags.
05
Step 5. Create Log Now button and assign ADODB INSERT script.
06
Step 6. Show SYS_DBStatus on screen for success/error feedback.
07
Step 7. Add On Error Resume Next and check Err.Number after connection and execute.
08
Step 8. Verify rows using SELECT TOP 20 query in SQL Server.
09
Step 9. Simulate SQL connection failure and confirm error message on HMI.
10
Step 10. Daily assignment: prepare SQL table screenshot, WinCC screen and successful insert record.
SQL Example 1Day 02
-- Run in SQL Server Management Studio
USE Softwell_DB;
CREATE TABLE InternalTagLog (
  Id           INT IDENTITY(1,1) PRIMARY KEY,
  LogTime      DATETIME          NOT NULL DEFAULT GETDATE(),
  BatchNo      NVARCHAR(50),
  SetPoint     FLOAT,
  ActualValue  FLOAT,
  OperatorName NVARCHAR(100),
  ShiftName    NVARCHAR(20)
);
VBScript Example 2Day 02
Dim cn, sql, connStr
Set cn = CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;" & _
          "Data Source=.\SQLEXPRESS;" & _
          "Initial Catalog=Softwell_DB;" & _
          "Integrated Security=SSPI;"
cn.Open connStr

sql = "INSERT INTO InternalTagLog" & _
      "(LogTime, BatchNo, SetPoint, ActualValue, OperatorName, ShiftName) VALUES (" & _
      "GETDATE(), '" & SmartTags("INT_BatchNo")      & "', " & _
                        SmartTags("INT_SetPoint")       & ", " & _
                        SmartTags("INT_ActualValue")    & ", '" & _
                        SmartTags("INT_OperatorName")   & "', '" & _
                        SmartTags("INT_ShiftName")      & "')"

cn.Execute sql
cn.Close
Set cn = Nothing
VBScript Example 3Day 02
Dim cn, sql, connStr, errMsg
On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;" & _
          "Initial Catalog=Softwell_DB;Integrated Security=SSPI;"
cn.Open connStr

If Err.Number <> 0 Then
  SmartTags("SYS_DBStatus") = "CONN ERR: " & Err.Description
  Err.Clear
Else
  sql = "INSERT INTO InternalTagLog(LogTime, BatchNo, SetPoint, ActualValue) VALUES (" & _
        "GETDATE(), '" & SmartTags("INT_BatchNo") & "', " & _
        SmartTags("INT_SetPoint") & ", " & SmartTags("INT_ActualValue") & ")"
  cn.Execute sql
  If Err.Number <> 0 Then
    SmartTags("SYS_DBStatus") = "SQL ERR: " & Err.Description
    Err.Clear
  Else
    SmartTags("SYS_DBStatus") = "OK " & Now()
  End If
  cn.Close
End If
Set cn = Nothing
On Error GoTo 0
Runtime Check: After Day 02, verify tag values, DB status tag, SQL rows and screenshots before moving to next day.

Daily Practice / Viva

Explain code line-by-line, show Runtime working screen, SQL query result and one troubleshooting point for Day 02.

DAY 03

Softwell WinCC VBScript — Handwritten M-Step Manual

External PLC Tag Logging to SQL Server

Practical Outcome: Log live PLC/OPC/S7 process values from WinCC external tags into SQL with quality and batch information.

External TagsPLC ValuesProcessTagLogQuality CodeBatch Logging
Trainer Note: First create tags and screen objects, then paste VBScript code in correct button action / cyclic action. Always test in Runtime and verify SQL result.
01
Step 1. Create external PLC tags EXT_Reactor_Temp, EXT_Reactor_Pressure, EXT_FlowRate and EXT_AgitatorRPM.
02
Step 2. Set tag update cycle and verify online value display in Tag Management.
03
Step 3. Create ProcessTagLog table with LogTime, TagName, TagValue, Unit, QualityCode and BatchNo.
04
Step 4. Prepare tagNames and tagUnits arrays inside VBScript.
05
Step 5. Open one ADODB connection and log multiple tag values in a For loop.
06
Step 6. Add IsNumeric check before SQL INSERT.
07
Step 7. Add QualityCode check and log only good-quality PLC values.
08
Step 8. Write SYS_DBStatus with last logging result and time.
09
Step 9. Verify average, maximum and minimum values using SQL GROUP BY query.
10
Step 10. Daily assignment: submit query result and Runtime screen showing external values.
SQL Example 1Day 03
-- SQL table for external (PLC) process data
USE Softwell_DB;
CREATE TABLE ProcessTagLog (
  Id             INT IDENTITY(1,1) PRIMARY KEY,
  LogTime        DATETIME          NOT NULL DEFAULT GETDATE(),
  TagName        NVARCHAR(100)     NOT NULL,
  TagValue       FLOAT,
  Unit           NVARCHAR(20),
  QualityCode    INT,
  BatchNo        NVARCHAR(50)
);
CREATE INDEX IX_ProcessLog_Time ON ProcessTagLog(LogTime DESC);
CREATE INDEX IX_ProcessLog_Tag  ON ProcessTagLog(TagName, LogTime DESC);
VBScript Example 2Day 03
'Cyclic action: LogPLCTagsToSQL  (cycle: 5 s)
Dim cn, connStr, cmd, rs
Dim tagNames(3), tagUnits(3), i
Dim val, batchNo

tagNames(0) = "EXT_Reactor_Temp"     : tagUnits(0) = "degC"
tagNames(1) = "EXT_Reactor_Pressure" : tagUnits(1) = "bar"
tagNames(2) = "EXT_FlowRate"         : tagUnits(2) = "L/min"
tagNames(3) = "EXT_AgitatorRPM"      : tagUnits(3) = "rpm"

batchNo = SmartTags("INT_BatchNo")

On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;" & _
          "Initial Catalog=Softwell_DB;Integrated Security=SSPI;"
cn.Open connStr

If Err.Number = 0 Then
  For i = 0 To 3
    val = SmartTags(tagNames(i))
    If IsNumeric(val) Then
      cn.Execute "INSERT INTO ProcessTagLog(LogTime,TagName,TagValue,Unit,BatchNo)" & _
                 " VALUES(GETDATE(),'" & tagNames(i) & "'," & val & _
                 ",'" & tagUnits(i) & "','" & batchNo & "')"
    End If
  Next
  SmartTags("SYS_DBStatus") = "PLC LOG OK " & Now()
  cn.Close
Else
  SmartTags("SYS_DBStatus") = "CONN ERR: " & Err.Description
  Err.Clear
End If
Set cn = Nothing
On Error GoTo 0
VBScript Example 3Day 03
'Extended cyclic logger with quality check
Dim cn, i, val, qual, tagName, batchNo
Dim tagNames(3)
tagNames(0) = "EXT_Reactor_Temp"
tagNames(1) = "EXT_Reactor_Pressure"
tagNames(2) = "EXT_FlowRate"
tagNames(3) = "EXT_AgitatorRPM"

batchNo = SmartTags("INT_BatchNo")

On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;" & _
        "Initial Catalog=Softwell_DB;Integrated Security=SSPI;"

If Err.Number = 0 Then
  For i = 0 To 3
    tagName = tagNames(i)
    val  = SmartTags(tagName)
    qual = SmartTags(tagName).QualityCode   'WinCC quality 192 = Good
    If IsNumeric(val) And qual = 192 Then
      cn.Execute "INSERT INTO ProcessTagLog(LogTime,TagName,TagValue,QualityCode,BatchNo)" & _
                 " VALUES(GETDATE(),'" & tagName & "'," & val & "," & qual & ",'" & batchNo & "')"
    End If
  Next
  cn.Close
End If
Set cn = Nothing
On Error GoTo 0
Runtime Check: After Day 03, verify tag values, DB status tag, SQL rows and screenshots before moving to next day.

Daily Practice / Viva

Explain code line-by-line, show Runtime working screen, SQL query result and one troubleshooting point for Day 03.

DAY 04

Softwell WinCC VBScript — Handwritten M-Step Manual

Conditional Logic IF / ELSE Writing to SQL

Practical Outcome: Use If, ElseIf, Select Case, threshold logic, shift detection and de-bounce before writing events to SQL.

IF ELSEThresholdEventLogShift LogicDe-bounce
Trainer Note: First create tags and screen objects, then paste VBScript code in correct button action / cyclic action. Always test in Runtime and verify SQL result.
01
Step 1. Create EventLog SQL table for THRESHOLD, WARNING, SHIFT and FAULT events.
02
Step 2. Create previous-value or previous-fault tags for de-bounce logic.
03
Step 3. Read temperature, pressure and flow external tags using SmartTags.
04
Step 4. Use If / ElseIf to classify high warning and critical threshold conditions.
05
Step 5. Use one fault-logged bit to avoid duplicate inserts on every scan cycle.
06
Step 6. Reset the fault-logged bit only after process values return to normal.
07
Step 7. Use Select Case True to detect A/B/C shift from system time.
08
Step 8. Log shift change event only when current shift differs from previous shift.
09
Step 9. Verify EventLog table with SQL queries for threshold and shift events.
10
Step 10. Daily assignment: trigger one warning, one critical and one shift-change record.
VBScript Example 1Day 04
'De-bounce pattern: only write when state changes
Dim curState, prevState
curState  = SmartTags("EXT_Reactor_Temp")
prevState = SmartTags("INT_PrevReactorTemp")

If Abs(curState - prevState) > 0.5 Then
  'Value changed by more than 0.5 degrees - log it
  SmartTags("INT_PrevReactorTemp") = curState
  '...INSERT to SQL...
End If
SQL Example 2Day 04
-- EventLog table for condition-based logging
USE Softwell_DB;
CREATE TABLE EventLog (
  Id          INT IDENTITY(1,1) PRIMARY KEY,
  EventTime   DATETIME      NOT NULL DEFAULT GETDATE(),
  EventType   NVARCHAR(50)  NOT NULL,  -- 'THRESHOLD','SHIFT','FAULT'
  TagName     NVARCHAR(100),
  TagValue    FLOAT,
  Description NVARCHAR(255),
  ShiftName   NVARCHAR(20),
  OperatorName NVARCHAR(100)
);
VBScript Example 3Day 04
'Cyclic action: ThresholdLogger (cycle: 2 s)
Dim temp, pressure, flow, desc, evType
Dim cn, prevFaultFlag

temp     = SmartTags("EXT_Reactor_Temp")
pressure = SmartTags("EXT_Reactor_Pressure")
flow     = SmartTags("EXT_FlowRate")
prevFaultFlag = SmartTags("INT_FaultLogged")

desc   = ""
evType = ""

If temp > 95 Then
  evType = "THRESHOLD"
  desc   = "CRITICAL: Reactor Temp = " & temp & " degC (limit 95)"
ElseIf temp > 85 Then
  evType = "WARNING"
  desc   = "HIGH WARN: Reactor Temp = " & temp & " degC"
End If

If pressure > 8 Then
  evType = "THRESHOLD"
  desc   = desc & " | CRIT PRESSURE: " & pressure & " bar"
End If

If flow < 5 And flow >= 0 Then
  evType = "THRESHOLD"
  desc   = desc & " | LOW FLOW: " & flow & " L/min"
End If

'Only log if new fault detected and not already logged
If evType <> "" And prevFaultFlag = 0 Then
  On Error Resume Next
  Set cn = CreateObject("ADODB.Connection")
  cn.Open "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;" & _
          "Initial Catalog=Softwell_DB;Integrated Security=SSPI;"
  If Err.Number = 0 Then
    cn.Execute "INSERT INTO EventLog(EventTime,EventType,TagName,TagValue,Description)" & _
               " VALUES(GETDATE(),'" & evType & "','REACTOR'," & temp & ",'" & desc & "')"
    cn.Close
    SmartTags("INT_FaultLogged") = 1
  End If
  Set cn = Nothing
  On Error GoTo 0
ElseIf evType = "" Then
  SmartTags("INT_FaultLogged") = 0   'Reset when conditions return to normal
End If
Runtime Check: After Day 04, verify tag values, DB status tag, SQL rows and screenshots before moving to next day.

Daily Practice / Viva

Explain code line-by-line, show Runtime working screen, SQL query result and one troubleshooting point for Day 04.

DAY 05

Softwell WinCC VBScript — Handwritten M-Step Manual

Alarms, Recipes and Trends via VBScript

Practical Outcome: Build final VBScript integration: alarm logging, SQL recipe load/save and SQL-based custom trend data.

AlarmLogRecipeDataLoad RecipeSave RecipeSQL Trend
Trainer Note: First create tags and screen objects, then paste VBScript code in correct button action / cyclic action. Always test in Runtime and verify SQL result.
01
Step 1. Create AlarmLog table for alarm time, alarm number, class, text, state and operator.
02
Step 2. Create RecipeData table for recipe name and setpoint parameters.
03
Step 3. Create alarm state script using Select Case to convert alarm bit state into text.
04
Step 4. Insert alarm event into SQL when alarm state changes.
05
Step 5. Create LoadRecipe button that reads selected recipe from SQL Recordset.
06
Step 6. Write SQL recipe values into WinCC setpoint tags.
07
Step 7. Create SaveRecipe button to insert current setpoints as a new recipe.
08
Step 8. Create RefreshTrend script to read last 30 minutes of process data from SQL.
09
Step 9. Populate TREND_Value_1..60 and TREND_Time_1..60 tags for custom display.
10
Step 10. Final assignment: demonstrate tag transfer, internal/external logging, event logic, alarm log, recipe and trend.
SQL Example 1Day 05
-- AlarmLog table for custom alarm history
USE Softwell_DB;
CREATE TABLE AlarmLog (
  Id           INT IDENTITY(1,1) PRIMARY KEY,
  AlarmTime    DATETIME     NOT NULL DEFAULT GETDATE(),
  AlarmNo      INT,
  AlarmClass   NVARCHAR(50),
  AlarmText    NVARCHAR(255),
  AlarmState   NVARCHAR(20),  -- CAME_IN / WENT_OUT / ACKED
  TagName      NVARCHAR(100),
  TagValue     FLOAT,
  OperatorName NVARCHAR(100),
  ShiftName    NVARCHAR(20)
);
VBScript Example 2Day 05
'Tag change action on alarm bit tag @OM_ALM_1
'Triggered when alarm state bit changes
Dim cn, alarmState, alarmText, stateStr

alarmState = SmartTags("@OM_ALM_1")
alarmText  = "High Temperature Reactor 01"

Select Case alarmState
  Case 1: stateStr = "CAME_IN"
  Case 2: stateStr = "WENT_OUT"
  Case 4: stateStr = "ACKED"
  Case Else: stateStr = "UNKNOWN"
End Select

On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;" & _
        "Initial Catalog=Softwell_DB;Integrated Security=SSPI;"
If Err.Number = 0 Then
  cn.Execute "INSERT INTO AlarmLog(AlarmTime,AlarmNo,AlarmClass,AlarmText,AlarmState," & _
             "TagName,TagValue,OperatorName,ShiftName)" & _
             " VALUES(GETDATE(),1,'HIGH_TEMP','" & alarmText & "','" & stateStr & _
             "','EXT_Reactor_Temp'," & SmartTags("EXT_Reactor_Temp") & _
             ",'" & SmartTags("INT_OperatorName") & _
             "','" & SmartTags("SYS_CurrentShift") & "')"
  cn.Close
End If
Set cn = Nothing
On Error GoTo 0
SQL Example 3Day 05
-- Recipe parameters table
USE Softwell_DB;
CREATE TABLE RecipeData (
  Id          INT IDENTITY(1,1) PRIMARY KEY,
  RecipeName  NVARCHAR(100) NOT NULL,
  Param_TempSP      FLOAT,
  Param_PressureSP  FLOAT,
  Param_FlowSP      FLOAT,
  Param_MixTime     INT,
  Param_AgitatorRPM INT,
  CreatedBy   NVARCHAR(100),
  CreatedAt   DATETIME DEFAULT GETDATE()
);
VBScript Example 4Day 05
'Button action: LoadRecipe
'Reads selected recipe from SQL and writes SP tags
Dim cn, rs, sql, recipeName
recipeName = SmartTags("INT_SelectedRecipe")  'e.g. "BATCH_A"

On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;" & _
        "Initial Catalog=Softwell_DB;Integrated Security=SSPI;"

sql = "SELECT TOP 1 * FROM RecipeData WHERE RecipeName='" & recipeName & "'"
rs.Open sql, cn

If Not rs.EOF Then
  SmartTags("INT_TempSP")      = rs("Param_TempSP")
  SmartTags("INT_PressureSP")  = rs("Param_PressureSP")
  SmartTags("INT_FlowSP")      = rs("Param_FlowSP")
  SmartTags("INT_MixTime")     = rs("Param_MixTime")
  SmartTags("INT_AgitatorRPM") = rs("Param_AgitatorRPM")
  SmartTags("SYS_DBStatus")    = "RECIPE LOADED: " & recipeName
Else
  SmartTags("SYS_DBStatus") = "ERR: Recipe not found - " & recipeName
End If

rs.Close : cn.Close
Set rs = Nothing : Set cn = Nothing
On Error GoTo 0
Runtime Check: After Day 05, verify tag values, DB status tag, SQL rows and screenshots before moving to next day.

Daily Practice / Viva

Explain code line-by-line, show Runtime working screen, SQL query result and one troubleshooting point for Day 05.

☎ Call 🟢 WhatsApp ✉ Enquire Now