首页 > 解决方案 > VBA - 我的函数需要一个参数 ByRef instaed of ByVal

问题描述

我遇到了一个奇怪的情况。我在 Windows 10 上使用 MS Access Office 365。

调用者的一个参数被改变。这意味着 strBase 被视为 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

调用方就在下面。

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

获得返回值后发生的事情是 txtPath 也发生了变化。但是,如果我将其修改为

AvailableDirPath(ByVal strBase as String) As String

然后,txtPath 没有改变。

我认为默认参数采用 ByVal,但为什么它采用 ByRef?

标签: vbaoffice365

解决方案


正如@Mark 提到的,默认值为 ByRef。因此,如果您不打算修改参数,则需要在参数中显式定义 ByVal。

这是MS解释的链接。

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


推荐阅读