2013-10-16 117 views
1

我期待做一個可以找到和替換數據的excel腳本,但對於所有我無法弄清楚如何編寫它的愛情。VBA Excel查找並替換沒有替換項目已被替換

現狀:

A-----------B-----------C

Cat-------Dog------Banana

Dog------Fish------Apple

Fish------Cat-------Orange

所以宏將看在B列單元格中的數據,再看看在C列中相鄰的單元格,並與替換數據的所有實例列一個什麼如果發現C.那麼結果將是:

A---------------B-----------C

Orange------Dog------Banana

Banana------Fish------Apple

Apple--------Cat-------Orange

但是這還不是全部,我想它不會改變細胞已經被更換一次! (我試圖改變背景顏色)

任何幫助嗎?我完全喪失了。

編輯:

好吧,我發現瞭如何做最簡單的部分(替換),但我不能找出如何改變不了已經被更換一次電池。這裏是我的代碼:

Sub multiFindNReplace() 
    Dim myList, myRange 
    Set myList = Sheets("sheet1").Range("A2:B3") 'two column range where find/replace pairs are 
    Set myRange = Sheets("sheet1").Range("D2:D5") 'range to be searched 
    For Each cel In myList.Columns(1).Cells 
    myRange.Replace what:=cel.Value, replacement:=cel.Offset(0, 1).Value, ReplaceFormat:=True 
    Next cel 
End Sub 

據我所知,ReplaceFormat:=真 沒有做任何事情,/使已經被更換一次還是被替換的物品!有沒有辦法以某種方式使這項工作?

回答

3

這裏的答案用你的建議與顏色一次性限制器:

Sub Replace_Once() 

'Find last row using last cell in Column B 
LastRow = Range("B" & Rows.Count).End(xlUp).Row 

'Clear colors in Column A 
Range("A1:A" & LastRow).Interior.ColorIndex = xlNone 

'Look at each cell in Column B one at a time (Cel is a variable) 
For Each Cel In Range("B1:B" & LastRow) 
    'Compare the cell in Column B with the Value in Column A one at a time (C is a variable) 
    For Each C In Range("A1:A" & LastRow) 
     'Check if the Cell in Column A matches the Cell in Column B and sees if the color has changed. 
     If C.Value = Cel.Value And C.Interior.Color <> RGB(200, 200, 200) Then 
      'Colors the cell 
      C.Interior.Color = RGB(200, 200, 200) 
      'Updates the value in Column A with the cell to the right of the Cell in Column B 
      C.Value = Cel.Offset(0, 1).Value 
     End If 
    Next 
Next 

'Uncomment the line below to remove color again 
'Range("A1:A" & LastRow).Interior.ColorIndex = xlNone 

End Sub 
+0

謝謝您的回答!我還是VBA的新手,所以我無法理解這段代碼。哪一行正在更改以及哪些行正在用於更改該行? – genuinelycurious

+0

現在的代碼是否清晰?您也可以通過反覆按F8來逐行遍歷每一行來測試它,並觀察發生了什麼。 –

+0

真是太棒了!由於某些原因,範圍(「B1:B」和LastRow)似乎不起作用。當我將其更改爲特定範圍時,它的作用就像一個魅力,但是當它使用LastRow時,它似乎不起作用。 編輯:弄清楚爲什麼,當列B的長度不等於A時,它不會將宏應用於列A比B長的部分。是否有可能規避此問題? – genuinelycurious