开发者

How do I pass a Range to a Sub in Word VBA?

开发者 https://www.devze.com 2022-12-26 14:02 出处:网络
I know this sounds simple, but seemingly it is not. If I write this in Word VBA, it always says 开发者_运维百科\"incompatible types\" - why?

I know this sounds simple, but seemingly it is not.

If I write this in Word VBA, it always says 开发者_运维百科"incompatible types" - why? And how do I make it work?

Sub GetRange()
   Dim r As Range
   Set r = ActiveDocument.Paragraphs(5).Range

   ProcessRange (r)
End Sub

Sub ProcessRange(r As Range)
    Debug.Print "This generates an error (incompatible types)- why?"
End Sub


It is not allowed to call a Sub with parenthesis, except if you are using the Call statement.

Hence you have to use either:

Call ProcessRange(r)

Or:

ProcessRange r

The reason for that is that in VBA (and VBS, VB6, too) the parenthesis can have a whole lot of different meanings.

In your case the range object will be evaluated before passing the result to ProcessRange. In this case it leads to a string being passed to the sub, because the default property of Range is Text.

See this article for an overview: http://blogs.msdn.com/ericlippert/archive/2003/09/15/52996.aspx


Process Range is a sub so don't invoke it with parentheses. (The error occurs because (r) causes r to be evaluated which returns its default property value which isn't of type range so mismatches what ProcessRange expects.

Use either;

ProcessRange r

or

call ProcessRange(r)


Using parenthesis visual basic assumes you're calling a function.

ProcessRange r

does the trick

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号