VBA 宏可在选择单元格时更改范围内单元格的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20806512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:07:05  来源:igfitidea点击:

VBA macro to change color of cells in range when a cell is selected

excel-vbavbaexcel

提问by MattB

I'm trying to write code that will, when a user selects a cell within a range, change the color of all the cells in that range. When running the code posted below, i get an error "Object doesn't support this property or method". I noticed that if i edit the code to just paste a "1" in all the cells that it works just fine. What am I doing incorrectly?

我正在尝试编写代码,当用户选择一个范围内的单元格时,该代码将更改该范围内所有单元格的颜色。运行下面发布的代码时,出现错误“对象不支持此属性或方法”。我注意到,如果我编辑代码以在所有单元格中粘贴“1”,它就可以正常工作。我做错了什么?

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.range)

    If Not Intersect(Target, range("G1:I5")) Is Nothing Then
        For Each cell In range("G1:I5")
        cell.interier.ColorIndex = 10
        Next
    End If
End Sub

采纳答案by mechanical_meat

The error is simply a typo of Interior

该错误只是一个错字 Interior

...
cell.Interior.ColorIndex = 10
'#         ^  
...

回答by Gary's Student

You should be aware that you do not have to loop over the cells:

您应该知道您不必遍历单元格:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim r As Range
    Set r = Range("G1:I5")
    If Intersect(r, Target) Is Nothing Then Exit Sub
    r.Interior.ColorIndex = 10
End Sub