如何在不修改函数参数的情况下将For Each的Variant迭代器作为String参数传入?
解决VBA For Each迭代器传参编译错误的方法
问题场景
你有一个要求接收String类型参数的函数:
Function GetFilePathArrayFromDirectory(directoryPath As String) As String() 'some code here End Function
在For Each循环中使用默认声明为Variant的迭代器OutDirectoryPath传参时,出现编译错误,代码如下:
Dim OutDirectoryPath For Each OutDirectoryPath In OutFolderPaths Dim FilePathArray() As String FilePathArray = GetFilePathArrayFromDirectory(OutDirectoryPath) Next OutDirectoryPath
核心矛盾是迭代器默认是Variant类型,而函数要求String类型参数,且你不想修改函数的参数类型。
可行解决方案
方案1:显式声明迭代器为String类型
直接给迭代器指定String类型,编译时就能确定类型匹配,避免报错。注意:此方案要求OutFolderPaths集合中的所有元素都是String类型,否则运行时会触发类型不匹配错误。
修改后的代码:
Dim OutDirectoryPath As String ' 显式声明为String类型 For Each OutDirectoryPath In OutFolderPaths Dim FilePathArray() As String FilePathArray = GetFilePathArrayFromDirectory(OutDirectoryPath) Next OutDirectoryPath
方案2:传参时强制类型转换
如果无法确保OutFolderPaths的元素都是String,或者不想修改迭代器的声明,可以在传参时用CStr()函数将Variant类型的迭代器强制转换为String类型:
修改后的代码:
Dim OutDirectoryPath For Each OutDirectoryPath In OutFolderPaths Dim FilePathArray() As String FilePathArray = GetFilePathArrayFromDirectory(CStr(OutDirectoryPath)) ' 强制转换为String Next OutDirectoryPath
内容的提问来源于stack exchange,提问作者Kudor
相关产品推荐
相关产品推荐

