VB.NETTranslate Late-Bound VBScript to Early-Bound
Listing 1. Most VBScript event handlers, functions, and procedures build and run with Option Strict Off. The testFunctionVBScript code comes from a Microsoft.Public.InfoPath newsgroup example for calculating a running sum to display in an expression box. The code only requires one modification (Dim i) to build and run the VBScript. The testFunction upgrade to the VBScript code includes the type casts required to early-bind the objects and permit turning Option Strict On after removing the VBScript. Function testFunctionVBScript(ByVal objNodeSet) 'Imported VBScript code from InfoPath 'newsgroup. The extra parentheses are JScript 'detritus not required for VBScript or VBA Dim runningSum Dim i 'Added for Option Explicit On runningSum = 0 If (Not (objNodeSet Is Nothing)) Then For i = 0 To (objNodeSet.length - 1) Dim objNode objNode = objNodeSet.nextNode Dim objsampleAttr objsampleAttr = _ objNode.selectSingleNode _ ("@my:sampleAttr") Dim objsampleElement objsampleElement = _ objNode.selectSingleNode _ ("my:sampleElement") If ((Not (objsampleAttr Is _ Nothing)) And (Not _ (objsampleElement Is _ Nothing))) Then If ((IsNumeric _ (objsampleAttr.text)) And _ (IsNumeric _ (objsampleElement.text))) Then runningSum = runningSum + _ objsampleAttr.text + _ objsampleElement.text End If End If Next End If testFunctionVBSCript = runningSum End Function Public Function testFunction(ByVal objNodeSet _ As IXMLDOMNodeList) As Double 'Port of VBScript to Visual Basic .NET Dim intSum As Double = 0 Dim intCtr As Integer Try If Not objNodeSet Is Nothing Then For intCtr = 0 To objNodeSet.length - 1 Dim objNode As IXMLDOMNode = _ objNodeSet.nextNode() Dim objsampleAttr As IXMLDOMNode = _ objNode.selectSingleNode _ ("@my:sampleAttr") Dim objsampleElement As _ IXMLDOMNode = _ bjNode.selectSingleNode _ ("my:sampleElement") If Not (objsampleAttr Is Nothing) _ And Not (objsampleElement Is _ Nothing) Then If IsNumeric(objsampleAttr.text) _ And IsNumeric _ (objsampleElement.text) Then intSum = intSum + _ CType _ (objsampleAttr.text, _ Double) + _ CType(objsampleElement. _ text, Double) End If End If Next End If Return intSum Catch excSum As Exception thisXDocument.UI.Alert(excSum.Message + _ excSum.StackTrace) End Try End Function |