2014-01-23 30 views
0

我是一個初學者VBA試圖從一個有用的貢獻者重新利用一些代碼,我遇到了一個麻煩一些,我希望你能幫助我。VBA Range.find錯誤(不xlPart發現與對象變量未設置錯誤)

我有一個表(DATA2)和關鍵字在另一個(關鍵字)註釋字符串。我的目標是搜索評論併爲其分配一個類別,如果找到其中一個關鍵字的話。

下面的代碼工作,因爲我想在某些值(Data = Eric Keyword = Eric)。但是,在其他值上拋出「Object variable not set」錯誤,我假設因爲沒有找到值(Data=Ericlikespie Keyword = Eric OR Data=Emi No Keyword)

任何指針將是有益的。我查看了以前的答案,但大多數似乎與範圍設置問題有關。我意識到,可以手動使用條件格式或大索引+搜索公式來完成所有這些工作,但是我正在尋找更好的方法。

Sub Trail() 

'DECS 
Dim ws As Worksheet, Map As Worksheet 
Dim MapRange As range, UpdateRange As range, aCell As range, bCell As range 
On Error GoTo Err 

'DEFS 
Set ws = Worksheets("DATA2") 
Set Map = Worksheets("KEYWORDS") 
Set UpdateRange = ws.range("K:K") 
Set MapRange = Map.range("A:A") 

'COMPS 
For Each aCell In UpdateRange 
    Set bCell = MapRange.Find(What:=aCell, LookIn:=xlValues, _ 
       LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
       MatchCase:=False, SearchFormat:=False) 
    If Not bCell Is Nothing Then 
     aCell.Offset(0, -1) = bCell.Offset(0, 1) 
    End If 
Next 

Exit Sub 
Err: 
MsgBox Err.Description 

End Sub 
+0

@Siddharth潰敗感謝您對上面的代碼,它一直是非常有幫助,我學習 – Shakujin

+0

使用踏進代碼拋出錯誤,發現一些值後,就aCell.Offset行if語句 – Shakujin

回答

1

我解決了問題,用下面的代碼。查找表和目標表在Range.Find語句中切換。這導致精確匹配的工作,但部分(我要去的)失敗,無論代碼的語法如何。

我還添加了在FindNext中循環搜索每個關鍵字的所有出現,改變了錯誤處理,處理不匹配,以及現在的代碼運行正常。

Private Sub CommandButton3_Click() 


    Dim ws As Worksheet 
    Dim DataRange As Range, UpdateRange As Range, aCell As Range, bCell As Range 
    Dim cCell As Range 
    Dim keeper As Range 


    On Error Resume Next 
    Set ws = Worksheets("Sheet1") 
    Set UpdateRange = ws.Range("A1:A8") 
    Set DataRange = ws.Range("H1:H4") 

For Each aCell In DataRange 
    Set bCell = UpdateRange.Find(What:=aCell.Value, LookIn:=xlValues, LookAt:= _ 
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ 
    , SearchFormat:=False) 

If Not bCell Is Nothing Then 
    Set keeper = bCell 
    bCell.Offset(0, 1) = aCell.Offset(0, 1) 

     Do 
      Set bCell = UpdateRange.FindNext(After:=bCell) 

      If Not bCell Is Nothing Then 
       If bCell.Address = keeper.Address Then Exit Do 
        bCell.Offset(0, 1) = aCell.Offset(0, 1) 
      Else 
       Exit Do 
      End If 

     Loop 
Else 
' MsgBox "Not Found" 
    'Exit Sub 

    End If 
Next 
Exit Sub 
Err: 
MsgBox Err.Description 
End Sub 
1

我想你想用

If Not bCell Is Nothing Then 

而非aCell,因爲發現是Set bCell = MapRange.Find ...

+0

內謝謝,這解決了「未設置」的錯誤,發佈編輯後的變化。我將繼續關注「.find找不到部分匹配」問題。 – Shakujin

相關問題