2014-02-17 209 views
0

我有這樣的代碼:爲什麼這種類型不匹配?

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

a1是什麼類型?呼叫類型名稱: MsgBox TypeName(a1) – Rob

回答

1

首先要注意:

因爲你使用的參數爲.Columns("C")TRange parametr(用於.Range("C:C")它的工作原理)你的函數返回Type mismatch

在行For Each cell In TRange,你實際上遍歷,但不是單元格。這意味着cell變量包含整個列。

您可以通過在For Each cell In TRange之後添加Debug.Print cell.Address行輕鬆地檢查它,你會得到消息$C:$C

enter image description here

秒注意:

你的代碼是高度uneffective ..For 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 
1

您需要更改for循環以引用單元格。目前它正在將其作爲一個陣列拉入。要解決這樣做

'add the .Cells to the TRange to reference each cell 
For Each cell In TRange.Cells 
+0

該解決方案比來自simoco的解決方案更通用,但我選擇了他的(她的?),因爲它更好地解釋。 – Envite

+0

下次要求詳細的原因,我會離開一個。我回答了你爲什麼不能像這樣調用cstr()。 – Sorceri

相關問題