简体   繁体   English

VBA:特定值中的颜色单元格,具体取决于值

[英]VBA: Color cells in a certain column, depending on value

Today, I had to deal with VBA the first time. 今天,我不得不第一次与VBA打交道。 After about 2 hours of research, I gave up and ended up asking this question, which is rather simple to undrstand: 经过大约2个小时的研究,我放弃了并最终提出了这个问题,这很容易理解:

On my excel Pivot, I search a column with a specific header "Percentage". 在我的excel Pivot上,我搜索具有特定标题“ Percentage”的列。 After I found this column, I want to color the cells, depending on their value. 找到此列后,我要根据单元格的颜色为其着色。 ( >1 green, <0.9 red, <1 und >=0.9 yellow) (> 1绿色,<0.9红色,<1 und> = 0.9黄色)

So far, I found the column (because it's not always the same column, I have to search for it). 到目前为止,我找到了该列(因为它并不总是同一列,所以我必须搜索它)。 But after I want to access the value of the cell, I get a type missmatch error(13) 但是,当我想访问单元格的值后,我收到类型不匹配错误(13)

Sub test()
Dim x As Range
    Cells.Find(What:="Percentage", After:=ActiveCell, LookIn:=xlFormulas _
        , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate

    For Each x In ActiveCell.EntireColumn
        If x.Value > 1 Then
            x.Interior.ColorIndex = 10
        End If
    Next x
End Sub

As you can see, I iterate through the column. 如您所见,我遍历该列。 Is this already wrong? 这已经错了吗?

I hope I could explain my problem properly and looking forward for some help 希望我能正确解释我的问题,并期待有所帮助

Unfortunately, looping through ActiveCell.EntireColumn doesn't return each individual cell, it just returns one Range , which is the entire column. 不幸的是,遍历ActiveCell.EntireColumn不会返回每个单元格,它只会返回一个Range ,即整个列。 Try looping by index instead: 尝试按索引循环:

Sub test()
    Dim columnNumber As Long
    columnNumber = Cells.Find(What:="Percentage", After:=ActiveCell, LookIn:=xlFormulas _
        , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Column
    Dim i As Long
    For i = 1 To ActiveSheet.UsedRange.Rows.Count
        If Cells(i, columnNumber).Value > 1 Then
            Cells(i, columnNumber).Interior.ColorIndex = 10
        End If
    Next i
End Sub

You should loop through: 您应该遍历:
ActiveCell.EntireColumn.Cells
On the other hand, looping trough entire column does not seem tobe a very good idea, you should try conditional formatting as Jordan mentioned, or try to retrieve range used by your table. 另一方面,遍历整个列似乎不是一个好主意,您应该尝试使用Jordan提到的条件格式,或者尝试检索表所使用的范围。

Thanks for your replies. 多谢您的回覆。 I tried to do it with conditional formattig, but it is it even possible since the position of my column changes monthly? 我尝试使用条件formattig来执行此操作,但是由于我的列位置每月更改一次,是否有可能?

@bobajob I tried to run your code, but I got an typemissmatch(13) error here: @bobajob我尝试运行您的代码,但是在这里遇到typemissmatch(13)错误:

 If Cells(i, columnNumber).Value > 1 Then 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM