VBA:Excel如果崩溃

我知道这个函数可以正常工作,但是当我试图填写我的电子表格时,Excel几乎立即崩溃。 当我进入debugging模式时,告诉我End If有问题。 我相信这是正确的,因为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 

让循环仅限于第一列和该表中使用的范围:

  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