Takeo Nishioka
Takeo Nishioka

Reputation: 387

VBA - my function takes an arument ByRef instaed of ByVal

I am encounting a strange situation. I am using MS Access Office 365 on Windows 10.

A parameter of caller is changed. It means strBase treated as ByRef.

Public Function AvailableDirPath(strBase As String) As String
' Find non existing folder path.
'   strBase : folder path that a folder is created.
'   Return: Full system path for the directory

    Dim bFound As Boolean: bFound = Falase
    
    Do Until FolderExists(strBase) = False
        ' The ParentFolderPath returns full path of parent folder. 
        strBase = ParentFolderPath(strBase) & "\" & (Int(99999 * Rnd) + 10000)
    Loop
    

    AvailableDirPath = strBase

End Function

The caller side is just below.

Dim txtPath As String: txtPath = "C:\windows\temp\MSACCESS_TEST\"
Dim strRes as String
strRes = modFileFolder.AvailableDirPath(txtPath)

What happens after getting return value was txtPath also changed. But If I modified it to

AvailableDirPath(ByVal strBase as String) As String

Then, txtPath is not changed.

I think Default parameter takes as ByVal but why it takes as ByRef?

Upvotes: 0

Views: 46

Answers (1)

Takeo Nishioka
Takeo Nishioka

Reputation: 387

As @Mark mentioned, the default was ByRef. So if you do not intend to modify the arguments then you will need to explicitly define ByVal in the parameters.

Here is the link to explained by MS.

https://learn.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/array-argument-must-be-byref

Upvotes: 1

Related Questions