3
votes

The function below accepts a word and checks if the word is in a list of words that is maintained in a public variable array. The calling sub passes an element of a string array to this function

 Function IsNormalCap(Mywrds As String) As Boolean

 If Right(Mywrds, 1) = "." Then Mywrds = Left(Mywrds, Len(Mywrds) - 1)

 i = 0
 Do While i < UBound(CapsType) + 1
      If (Mywrds <> CapsType(i)) Then
           i = i + 1
      Else
           Exit Do
      End If
 Loop
 If i = UBound(CapsType) + 1 Then
      IsNormalCap = False
 Else
      IsNormalCap = True
 End If
 End Function

Relevant lines from calling sub code:

 Dim buff() As String
 ....
 If (Not (IsNormalCap(buff(i + 1)))) Then
 ....code.....
 End if

Question:

buff(i+1) seems to be passed as a ByRef as the value of buff(i+1) is changing after the function is called. The words that contain period at the end are coming back to the sub without the period at the end. Why does this happen? Need some clarity on this as there are several such functions where such arguments are passed and I dont seem to know when the value is passed ByRef when the intention was to pass it as ByVal (and vice versa). Thanks in advance. Please let me know if I have been clear enough.

1
I learnt that ByRef is the default. msdn.microsoft.com/en-us/library/aa263527(v=vs.60).aspx But then why has this not happened before?Peekay

1 Answers

4
votes

In Function declarations, parameters that are not specified as ByRef or ByVal, are by default ByRef

Extract from VBA help

ByVal Optional. Indicates that the argument is passed by value.
ByRef Optional. Indicates that the argument is passed by reference.ByRef is the default in Visual Basic.

So, if you always want ByVal, specify that

Function IsNormalCap(ByVal Mywrds As String) As Boolean

If, on the other hand, you sometimes want ByRef and other times ByVal, you can override ByRef in the function call by enclosing the parameter in ()

Eg If function is defined as

Function IsNormalCap(ByRef Mywrds As String) As Boolean

or

Function IsNormalCap(Mywrds As String) As Boolean

then

If Not IsNormalCap((buff(i + 1))) Then

will pass buff(i + 1) by value

Note, I've removed some redundant () from your code to aid clarity.