Search code examples
vbafunctiontypesparameters

How can I use an iterator from a "For Each" as a String parameter to a function when all iterators are declared as "Variant"?


So I'm trying to use the iterator OutDirectoryPath from a "For Each" block as a parameter to this function:

Function GetFilePathArrayFromDirectory(directoryPath As String) As String()
    'some code here
End Function

Here is how I pass it:

Dim OutDirectoryPath
For Each OutDirectoryPath In OutFolderPaths
        
        Dim FilePathArray() As String
        
        FilePathArray = GetFilePathArrayFromDirectory(OutDirectoryPath)
    
Next OutDirectoryPath

The problem is that I get a Compile Error because every iterator from a "For Each" block is declared automatically as a "Variant", and it is assigned as a String only at runtime. My question is how can I use iterators as parameters if they will always have the "Variant" type, without changing the function's arguments to "Variant"?


Solution

  • You can convert a variant to a string by using CStr:

    FilePathArray = GetFilePathArrayFromDirectory(CStr(OutDirectoryPath))