What is behind this difference in parentheses effect in VBA?

后端 未结 2 1504
暖寄归人
暖寄归人 2020-12-18 15:40

I\'ve not seen this in other languages but I see it a lot in VBA (which I just started working with). Suppose you have a table in Word and wish to set the rows to a certain

2条回答
  •  渐次进展
    2020-12-18 15:48

    The most serious consequence of using parentheses inappropriately can best be demonstrated by code such as:

    Sub Test()
        Dim r As Range
        Set r = Range("A1")
        TestSub r
        TestSub (r)
    End Sub
    
    Sub TestSub(parm As Range)
        MsgBox parm.Address
    End Sub
    

    In that code TestSub r correctly passes a range object to TestSub. However, placing parentheses around the r, i.e. TestSub (r) causes VBA to evaluate r using its Value property and is therefore equivalent to TestSub r.Value. This then gives an error as it is passing a Variant (maybe a Variant/Double with a value of 123.45) to a subroutine that is expecting a Range.


    It is basically just incorrect syntax to enclose parameters to a Subroutine within parentheses. They should only be used when a Function is returning a value.


    P.S. I apologise that my example is Excel VBA. I hadn't noticed that the question was Word VBA, plus I could knock up an Excel example quicker than I could research Word VBA enough to give an example in it. The principle is the same in both though.

提交回复
热议问题