首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的电子表格函数与从代码中调用时的行为不同?

为什么我的电子表格函数与从代码中调用时的行为不同?
EN

Stack Overflow用户
提问于 2013-03-29 01:28:33
回答 1查看 1K关注 0票数 5

当我从Excel (在单元格中)调用函数时:

代码语言:javascript
复制
=allVlookup(O24,A:D,3,"")

vs通过vba

代码语言:javascript
复制
MsgBox allVlookup(Range("O24"), Range("A:D"), 3, "")

我得到了不同的结果。当从Excel中调用时,我只得到第一个匹配项,但当从具有相同参数的vba测试子中调用时(除了将Range添加到参数以允许该子对象运行之外),我会得到完整的结果(不止一个)。

我使用的函数是:

代码语言:javascript
复制
Public Function allVlookup(lookupRange As Range, tableRange As Range, colIndex As Integer, Optional delimiter As String = "") As String

    Dim c As Range
    Dim firstAddress As String
    'MsgBox tableRange.Address  ' this is correct
    'With Sheets(4).Range("A1:C12").Columns(1)
    'With Range("A1:C12").Columns(1)

    'this doesn't allow things to work right either (???)
    'Set tableRange = Range("A:D")
    'Set lookupRange = Range("O24")

    'search only the first column for matches
    With tableRange.Columns(1)
        Set c = .Find(what:=lookupRange.Value, LookIn:=xlValues)

        If Not c Is Nothing Then

            firstAddress = c.Address

            Do
                'add the delimiter
                If (allVlookup <> "") Then
                    allVlookup = allVlookup + delimiter
                End If

                'append value to previous value
                allVlookup = allVlookup + c.Offset(0, colIndex).Value


                Set c = .FindNext(c)
                'exit conditions
                'no match found
                If (c Is Nothing) Then
                    Exit Do
                    'we're back to start
                ElseIf (c.Address = firstAddress) Then
                    Exit Do
                End If

            Loop
        End If
    End With

End Function

我无法解释为什么会发生这种情况。

我可以做些什么来使输出相同呢?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15688360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档