2

I am trying to understand something about about the way VBS splits single lines of code across multiple lines.

In the below function the _ character is used in two places to split execution across two lines, ok all fine.

For Each objItem in colItems
    if i=0 then
        header = ""
        For Each param in objItem.Properties_
            header = header & param.Name & vbTab
        Next
        WScript.Echo header
        i=1
    end if
    serviceData = ""
    For Each param in objItem.Properties_
        serviceData = serviceData & param.Value & vbTab
    Next
    WScript.Echo serviceData
Next

What I do not understand then is how this is supposed to look on a single line. When I modify either of the lines with any of the below I get an error.

  1. For Each param in objItem.Propertiesheader = header & param.Name & vbTab
  2. For Each param in objItem.Properties.header = header & param.Name & vbTab
  3. For Each param in objItem.Properties header = header & param.Name & vbTab

Errors to the effect of:

C:\Program Files (x86)\ManageEngine\AppManager12\working\conf\application\scripts\wmiget.vbs(86,2) Microsoft VBScript runtime error: Object doesn't support this property or method: 'objItem.PropertiesserviceData'

How would the above be correctly represented on a single line?

3therk1ll
  • 2,056
  • 4
  • 35
  • 64
  • Does this answer your question? [Breaking a String Across Multiple Lines](https://stackoverflow.com/questions/37564704/breaking-a-string-across-multiple-lines) – Tarik Aug 18 '20 at 16:12
  • @41686d6564 it's related because breaking strings makes use of the Line Continuation Character `_` but in this context not really. – user692942 Aug 18 '20 at 16:33

1 Answers1

2

The issue here is you are using the Line Continuation Character _ to continue a line when it isn't required.

You only use it if you need a single line of code to span multiple lines, using your example something like;

For Each _
param _
in _
objItem.Properties
    serviceData = serviceData & param.Value & vbTab
Next

will work (be it a bit pointless) because the single line

For Each param in objItem.Properties

is being spanned across multiple lines.

So, because the line;

For Each param in objItem.Properties

is a single line of code no continuation is required as the next line of code is expected. However, when you provide it, it causes VBScript to error with;

Microsoft VBScript compilation error: Expected end of statement

Which is VBScript's way of telling you that the line isn't finished and still expects the end of the code statement.

If you do want to span multiple code statements across a single line use colon (:) which acts as a statement seperator, i.e;

For Each param in objItem.Properties : serviceData = serviceData & param.Value & vbTab : Next

Useful Links

user692942
  • 16,398
  • 7
  • 76
  • 175