VBA:Excel在结束时崩溃

时间:2017-06-16 15:45:11

标签: excel vba excel-vba

我知道此功能可以正常工作,但是当我尝试在电子表格中填写时,它会导致Excel几乎立即崩溃。当我进入调试模式时,它告诉我在结束时有问题。我认为这是正确的,因为End If结束了之前的If语句。

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

'Update 20150310
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 '<-- crashes here
Next
MYVLOOKUP = xResult
End Function

1 个答案:

答案 0 :(得分:1)

允许将循环限制为仅第一列和该工作表上使用的范围:

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

'Update 20150310
Dim rng As Range
Dim xResult As String
'resets the range to only the first column and the used range.
'this will limit the cycling to the smallest possible range.
Set pWorkRng = Intersect(pWorkRng.Columns(1), pWorkRng.Parent.UsedRange)

xResult = ""
For Each rng In pWorkRng
    If rng = pValue Then
        xResult = xResult & " " & rng.Offset(0, pIndex - 1)
    End If 
Next
MYVLOOKUP = xResult
End Function