vba 赋值左侧的函数调用必须返回 Variant 或 Object,在两个数组中找到公共值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16157111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:46:24  来源:igfitidea点击:

Function call on left hand side of the assignment must return Variant or Object, finding common values in two arrays

arraysstringvbaexcel-vbafor-loop

提问by user2217895

I've got two arrays and I'm trying to pull out the common values in them and the function findUniques is supposed to return the strings (they're names) concatenated and separated by a comma. I think I'm close but I can't find what's wrong. I get an error in line 10

我有两个数组,我试图提取其中的公共值,函数 findUniques 应该返回连接并用逗号分隔的字符串(它们是名称)。我想我很接近,但我找不到出了什么问题。我在第 10 行出现错误

Function findUniques(astrArray1() As String, astrArray2() As String) As String

    Dim blnMP5 As Boolean
    blnMP5 = False
    Dim counter1 As Long
    Dim counter2 As Long

    For counter1 = LBound(astrArray1) To UBound(astrArray1)
        For counter2 = LBound(astrArray1) To UBound(astrArray2)
            If astrArray1(counter1) = astrArray2(counter2) Then
                blnMP5 = False
                If blnMP5 = True Then
                    findUniques() = findUniques & "," & "astrArray1()"
                End If
            End If
        Next counter2
    Next counter1

End Function

采纳答案by Marshall

Declare a variable to hold the string you are building

声明一个变量来保存您正在构建的字符串

Dim tempString as string

Dim tempString 作为字符串

And add this at line 10 tempString = tempString & "," & astrArray1(counter1)

并将其添加到第 10 行 tempString = tempString & "," & astrArray1(counter1)

And finally findUniques = tempString End function

最后 findUniques = tempString 结束函数

回答by Kenneth

Your error is in this line:

你的错误在这一行:

findUniques() = findUniques & "," & "astrArray1()"

You're trying to assign a value to a function call, which doesn't make sense.

您正在尝试为函数调用赋值,这是没有意义的。

You should declare a variable in the start of your function and keep on adding to that one and eventually return it:

您应该在函数的开头声明一个变量并继续添加到该变量并最终返回它:

Function findUniques(astrArray1() As String, astrArray2() As String) As String

    Dim blnMP5 As Boolean
    blnMP5 = False    
    Dim counter1 As Long
    Dim counter2 As Long  
    Dim uniquesString as String = ""

    For counter1 = LBound(astrArray1) To UBound(astrArray1)
        For counter2 = LBound(astrArray1) To UBound(astrArray2)
            If astrArray1(counter1) = astrArray2(counter2) Then
               blnMP5 = False
               If blnMP5 = True Then
                   uniquesString = uniquesString & "," & "astrArray1()"
               End If
             End If
        Next counter2
     Next counter1

End Function