I'm trying to run a code that upon pressing a button, finds a cell from a column ("H") in another sheet (labeled "MFG PNs") and matches its value with what is entered in cell "Z21" on my sheet labeled "SPC". Once the cell in H is found, I am trying to change the corresponding cell in column Q on the same row to a different color.
I am currently getting this error message: "Run time error 9, subscript out of range" It occurs at the color changing part of the code.
Sub Approve_Click()
Dim r As Long
Dim m As Long
m = Sheets("MFG PNs").Range("H3:H1200").Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For r = 1 To m
If Sheets("MFG PNs").Range("H" & r) = Sheets("SPC").Range("Z21") Then
Sheets("MFG PNs").Range("Q" & r).Interior.ColorIndex = RGB(0, 97, 0)
End If
Next r
End Sub
Color indexes are values that go from 1 to 56 (see below) RGB color values are usually quite a bit larger than this.
You can change .ColorIndex to .Color and enter an appropriate color, or change the RGB(0,97,0) to a specific index value.
VBA code is available here that generates color indexes and value on a worksheet.
While testing your code, I did find another problem: it crashes when the target string ("*") is not found. The correction below should account for that:
Set cell = Sheets("MFG PNs").Range("H3:H1200").Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If (Not cell Is Nothing) Then
For r = 1 To cell.Row
'YOUR CODE
Next r
End If
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.