将for-each对象传递给vba中的子​​或函数

时间:2016-09-14 17:28:49

标签: vba object foreach

当我调用sub pFileName时,我需要一个'对象'使用以下代码时出错:

Sub test()
Dim fs As Object
Dim csv As Object
Dim oFolder As Object

Set fs = CreateObject("Scripting.FileSystemObject")
Set oFolder = fs.getfolder(Application.CurrentProject.Path)

For Each csv In oFolder.files
    Debug.Print csv.Name
    pFname (csv)
Next csv
End Sub

Sub pFname(ByVal csv As Object)
    Debug.Print (csv.Name)
End Sub

我不确定为什么csv不被认为是对象 - 在子调用之前就没有Debug.Print语句证明它是一个对象?

1 个答案:

答案 0 :(得分:2)

您需要删除此行中的括号:pFname (csv)

将括号括在参数周围会强制它传递ByVal,并且您无法使用Object执行此操作,因为Object基本上是< / em>参考。这很好用:

Sub test()
Dim fs As Object
Dim csv As Object
Dim oFolder As Object

Set fs = CreateObject("Scripting.FileSystemObject")
Set oFolder = fs.getfolder(Application.CurrentProject.Path)

For Each csv In oFolder.files
    Debug.Print csv.Name
    pFname csv  '<-----
Next csv
End Sub

Sub pFname(ByVal csv As Object)
    Debug.Print csv.Name
End Sub