关于在单个单元格中返回多个值的VBA代码(宏)的说明

时间:2016-04-01 20:17:00

标签: excel vba excel-vba vlookup

我有一个用于excel的宏我在网上找到了创建一个&myverlookup'允许查找范围内数字的所有实例并返回指定的相应列的函数;必要时有多个实例。我已经获得了宏和各自的myvlookup以满足我的需求,但我想解释这段代码如何工作的逻辑/意义。代码如下,任何信息都会有所帮助。 P.S我的代码是文盲,所以不要以为我知道任何事情。谢谢!

Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)
Dim rng As Range
Dim xResult As String

xResult = ""

For Each rng In pWorkRng

    If rng = pValue Then
        xResult = xResult & " * " & rng.Offset(0, pIndex - 1)
    End If
Next

MYVLOOKUP = xResult

End Function

2 个答案:

答案 0 :(得分:4)

通过内联评论给出解释:

' Declare a custom function called MyVLOOKUP and specify 
' that 3 arguments must be passed to it when it is invoked.
' These arguments can be named any legal name, but the values
' that eventually get passed in must match the declarations for
' each argument (String, Range, Long Integer)
Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)

  ' Declare a variable that will represent a cell/range
  Dim rng As Range

  ' Declare a variable that will hold the function's overal result
  Dim xResult As String

  ' Initialize the result variable to an empty string
  xResult = ""

  ' Loop through each cell/range in the range that was passed into the
  ' function and stored under the argument name "pWorkRng". The "rng"
  ' variable just acts as a temporary identifier that represents each
  ' cell/range that is being looped over - one at a time.
  For Each rng In pWorkRng

    ' Check the cell/range that the loop is currently looping over
    ' to see if it matches the supplied argument ("pValue") that was
    ' passed in when the function was called.
    If rng = pValue Then
        ' If the cell/range is a match for the input argument
        ' set the function's return value variable to itself,
        ' concatenated with an asterisk character and the value 
        ' of the cell/range that is one column to the left of
        ' the cell/range being looped over. ("pIndex" is supplied
        ' to the function as a way to indicate what column the
        ' lookup is to be done in).
        xResult = xResult & " * " & rng.Offset(0, pIndex - 1)
    End If

  ' Loop to the next cell/range
  Next

  ' Now that the loop is finished, have the function return its
  ' final value, which will either be an empty string ("") if no
  ' cells/ranges match the input or the value of the cells that 
  ' are one column to the left of the found ranges.
  MYVLOOKUP = xResult

End Function

现在,在解释了代码后,我应该指出:

  If rng = pValue Then

应该更明确地写成:

  If rng.Value = pValue Then

而且:

  xResult = xResult & " * " & rng.Offset(0, pIndex - 1)

应该是:

  xResult = xResult & " * " & rng.Offset(0, pIndex - 1).Value

因为没有明确的.Value属性访问器,代码读取就好像要将Range对象与值进行比较,这些值不同。您想要将Range对象的VALUE与值进行比较。代码确实按照您的方式执行此操作,但它仅获取.Value,因为未指定任何属性且.Value是默认属性。明确是更好的。

答案 1 :(得分:3)

以下是我的回答:

{{1}}