0

I am trying to return a string from a subroutine in VBScript, but I am getting a type mismatch.

Here is the code:

main 

Sub Main
  Dim NumofBatches, Batch1 
  CStr(Batch1)
  Batch1 = checkXML("Bar.xml") 
End Sub

'Checks For Batch in ZoneX
Sub checkXML(sFile)
  Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("D:\Projects\Scripts\SQL\" + sFile, 1)
  Dim strLine, x, y
  Do While Not objFileToRead.AtEndOfStream
    CStr(StrLine)
    strLine = objFileToRead.ReadLine()
    'String Foo
    If (x > 3) Then
      If (InStr(strLine, """") = 1) Then
        CheckXMl = ""
      Else
        CheckXMl = StrLine
      End If
    End If
  Loop
  objFileToRead.Close
  Set objFileToRead = Nothing
End Sub

And I am not sure of the issue, I know the system right now only gets one result from If (x > 3) Then portion, but even if it weren't I should only overwrite my result, correct?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
levi Clouser
  • 338
  • 1
  • 4
  • 14
  • 4
    Use `Function() ... End Function` instead of `Sub() ... End Sub` to return a result. – omegastripes Oct 17 '16 at 19:43
  • hmm, this seems to work, but [this](http://stackoverflow.com/questions/15667421/vbscript-return-value-from-a-function) led me to believe otherwise.. – levi Clouser Oct 17 '16 at 19:46
  • The [answer](http://stackoverflow.com/a/15667474/6352151) to the question you posted is stating exactly what told by @omegastripes. And a quick FYI: This code --> `Cstr(StrLine)` is doing absolutely nothing in your code, plus I believe it is never even entering the `if` part, since you are never assigning any values to `x` :) – Victor Moraes Oct 17 '16 at 20:00
  • all the x assignment was boring stuff, simple string operations and batching to known values ect, added nothing to the issue, so I took it out and added the 'string foo in its place. – levi Clouser Oct 17 '16 at 20:18
  • BTW, variables passed as arguments to `Sub` or `Function` can be changed within it (if passed `ByRef` which is default), thus it's possible to return a number of values both from `Sub` and `Function`. – omegastripes Oct 18 '16 at 07:15

1 Answers1

2

As @omegastripes pointed out, subs don't have a return value, only functions do.

Change

Sub checkXML(sFile)
  ...
End Sub

to

Function checkXML(sFile)
  ...
End Function

See also.

Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328