2015-03-13 61 views
-1

我正在尝试更改单元格的颜色。我有代码阻止黑色背景被激活的单元格。这个效果很好,但是我想在按钮单击事件中将这些单元格中的某些单元格的背景更改为红色。Excel VBA偏移量未激活单元格

当按钮被点击时,我想让它周围的所有单元变成红色。由于无法选择细胞,我无法做到这一点。如果我使用Range(“A1”),Value =“Hi”(这是一个黑色背景的单元格),Hi会出现在那里,我认为这是因为我没有激活单元格而改变了它的值。

有没有办法偏离活动细胞,并改变它周围的细胞的颜色,而不激活/选择这些细胞?

代码在Worksheet_SelectionChange是:

'Stops users selecting a Black cell. If they try they are returned to  their previous cell 

If Target.Cells(1, 1).Interior.ColorIndex = 1 Then 
    OldRange.Select 
    'MsgBox "H" 
Else 
    Set OldRange = Target 
End If 

我在按钮点击的代码是:

If Range("AL7").Value = "Bomb" Then 
MsgBox "BOOM, BANG, KABOOM!!" 
ActiveCell.Interior.ColorIndex = 3 

ActiveCell.Offset(rowOffset:=0, columnOffset:=1).Select 
ActiveCell.Interior.ColorIndex = 3 

ActiveCell.Offset(rowOffset:=1, columnOffset:=0).Activate 
ActiveCell.Interior.ColorIndex = 3 

ActiveCell.Offset(rowOffset:=0, columnOffset:=-1).Activate 
ActiveCell.Interior.ColorIndex = 3 

ActiveCell.Offset(rowOffset:=0, columnOffset:=-1).Activate 
ActiveCell.Interior.ColorIndex = 3 
+0

你不能只是做“ActiveCell.Offset(0,1).interior .colorindex = 3“? – OpiesDad 2015-03-13 16:33:23

+0

[如何避免使用Excel中的VBA宏选择](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) – RubberDuck 2015-03-13 16:34:27

回答

0

你不必选择一个单元格来改变它的属性,实际上是被认为是糟糕的做法,以及许多人意想不到的后果。

相反,你可以做这样的事情:

ActiveCell.Offset(rowOffset:=0, columnOffset:=1).Interior.ColorIndex = 3 

而且具有焦点停留在你的细胞

+0

太棒了!谢谢! – Tom36 2015-03-13 16:42:35