2017-06-29 65 views
0

對於正在變大的Internet文檔,我試圖擺脫自動佈局,導致他們嚴重放慢了我們的Excel到延伸到不可用的地步。使用Excel宏更改Excel列背景顏色

我試圖創建一個基於活動單元格值爲單元格背景着色的宏。

Sub find() 

Dim CurValue As String 
Dim ColorIndex As String 
Dim Findr  As Range 
Dim MyRange As Range 

Set MyRange = ActiveCell 
CurValue = ActiveCell.Value 

With ActiveCell 
    Set Findr = Range("A1:A10").find(CurValue) 
    If Not Findr Is Nothing Then 
     ColorIndex = Findr.Offset(ColumnOffset:=1).Value 
     MyRange.Interior.ColorIndex = ColorIndex 
'  rngStart.Select 
    End If 
End With 

End Sub 

這個子作品完美。

但是,對於問題: 現在我想調用它,每當一個單元格發生變化時,但如果我調用宏,每當單元格更改在我的Sheet.I試圖使用工作表源代碼的每一個變化。 但是,它使用用戶在更改之後跳轉到的單元格,而不是之前編輯的單元格。

我如何得到這個宏來調用每個改變的單元而不是新的選擇單元?

+1

將代碼置於'WorkSheet_Change'而不是'WorkSheet_SelectionChange'? –

回答

0

把在相應的工作表對象以下應該工作:

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim CurValue As String 
Dim ColorIndex As String 
Dim Findr  As Range 
For Each AC In Target.Cells 
    CurValue = AC.Value 
    Set Findr = Range("A1:A10").find(CurValue) 
    If Not Findr Is Nothing Then 
     ColorIndex = Findr.Offset(ColumnOffset:=1).Value 
     AC.Interior.ColorIndex = ColorIndex 
    End If 
Next 
End Sub 

注 - A1的一個:A10需要爲空白,但在B下一空白值必須有一個ColorIndex值並且不能爲空。我建議零清空單元格外的所有顏色,但我看不到你的工作表的「空」單元格的樣子。

For..Each循環用於處理一次更換多個單元格的位置它會在每個更改的單元上執行顏色更改。

此外,由於公式更改而不是編輯而導致「更改」的單元格不會使用此方法更改。

+0

這個作品很有魅力,謝謝。 – Luuk