Can be true ByRef achieved in VBA?

pass-by-reference, vba

Solution

Not sure how much of this applies to VBA, but MSDN says that the calling code can force `ByVal` call if the output value does not have an "address", i.e. is not a variable, but the result of an evaluation, or function call, or an immediate constant etc.

Suppose `cCountOfPrintjobs` is a `Property Get` of the object `PdfCreator`. That means that actually there's a function that checks its internals of the objects, figures out how many print jobs there are, and returns that value. That value is returned "on stack", it doesn't have a fixed "address" to be polled by your code. To avoid reading invalid/unset memory areas, VBA will change the call to `ByVal`, so your code hangs, because there's nothing to change the argument value.

Later edit

z̫͋ already gave the answer in comment section...

Problem

After recent tests with PDF printer I found out that VBA's `ByRef` is not truly passing reference to variable as expected: Values of asychnronously changed variables are never updated when passed by reference. In the following simplified example, `ByRef Variable` parameter will never change its value: ``` '--- definition --- Private Sub WaitUntilEqual(ByRef Variable As Variant, ByVal Value As Variant) Dim PollingInterval as Integer = 200 Do While Variable <> Value TimeSpent = TimeSpent + PollingInterval Sleep PollingInterval Loop End Sub '--- usage (initializations omitted) --- PdfCreator.cPrint "filename1" PdfCreator.cPrint "filename2" PdfCreator.cPrint "filename3" 'at this point, PdfCreator.cCountOfPrintjobs is 0 and needs few seconds to raise to 3 WaitUntilEqual PdfCreator.cCountOfPrintjobs, 3 'this will stick forever - it shouldn't ``` Is this a VBA limitation? Can this be circumvented? I need this method 3-4 times (and it also includes extra features like timeout etc...) so I do not want to repeat entire wait loop via copy-paste.

Original source