Today, I had to deal with VBA the first time. After about 2 hours of research, I gave up and ended up asking this question, which is rather simple to undrstand:
On my excel Pivot, I search a column with a specific header "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)
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)
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. 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.
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?
@bobajob I tried to run your code, but I got an typemissmatch(13) error here:
If Cells(i, columnNumber).Value > 1 Then
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.