我有这段代码:
Public Function MultiVLookup(MatchWith As String, TRange As Range, col_index_num As Integer)
If (MatchWith = "") Then
MultiVLookup = ""
Else
For Each cell In TRange
a1 = cell.Value
a2 = CStr(a1) 'FAILURE IN THIS LINE
b = CStr(MatchWith)
If (a2 = b) Then
x = x & cell.Offset(0, col_index_num).Value & ", "
End If
Next cell
If (x = "") Then
MultiVLookup = ""
Else
MultiVLookup = Left(x, Len(x) - 2)
End If
End If
End Function
我称之为:
L_CurrentService = MultiVLookup(L_CurrentCI, Sheets("Servicios").Columns("C"), 2)
但它在上面标有“类型不匹配”的行中失败了,我无法找到原因。
为什么我不能这样调用CStr()?
答案 0 :(得分:1)
您需要更改for循环以引用单元格。截至目前,它正在将其作为阵列拉入。要解决这个问题
'add the .Cells to the TRange to reference each cell
For Each cell In TRange.Cells
答案 1 :(得分:1)
首先注意:
您的函数返回Type mismatch
,因为您使用参数.Columns("C")
表示TRange
parametr(对于.Range("C:C")
它有效)。
在行For Each cell In TRange
中,您实际上是循环遍历列,而不是单元格。这意味着cell
变量包含整个列。
您可以在Debug.Print cell.Address
之后添加第For Each cell In TRange
行来轻松检查 - 您会收到消息$C:$C
。
第二个注释:
您的代码非常无效 ..对于Excel 2007及更高版本,您将遍历所有1048576单元格。我建议你改用Find方法:
Public Function MultiVLookup(MatchWith As String, TRange As Range, col_index_num As Integer) As String
Dim rng As Range
Dim res As String
Dim sAddr As String
MultiVLookup = ""
If MatchWith = "" Then Exit Function
With TRange
Set rng = .Find(What:=MatchWith, LookAt:=xlWhole, MatchCase:=False)
If Not rng Is Nothing Then
sAddr = rng.Address
Do
res = res & rng.Offset(0, col_index_num).Value & ", "
Set rng = .FindNext(rng)
If rng Is Nothing Then Exit Do
Loop While rng.Address <> sAddr
End If
End With
If res <> "" Then MultiVLookup = Left(res, Len(res) - 2)
End Function