简体   繁体   中英

highlight cell if isblank vba

Hi i have the following code but it prommpts an error range of object_worksheet failed. I'm not sure what i'm doing wrong (i've found the vba code using record macro and simply copy and pasted except i've replaced all of selection to ws.range(emptyrow) to indicate the range is up to the last cell with values. Also, if i were to change the sub to sub highlightemptycell_change() and have if statement as such: "if any cells are changed then do the following" how would i write that in a vba language?

sub highlightemptycell()
    Dim ws As Worksheet
    Dim r As Range
    Dim emptyrow As Long
    Dim err As Range

    Set ws = Worksheets("Master")
    emptyrow = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1    '<<< safer....

    ws.Range(emptyrow).FormatConditions(1).StopIfTrue = False
    ws.Range(emptyrow).FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=ISBLANK(ws.range(emptyrow)"
    ws.Range(emptyrow).FormatConditions(ws.Range(emptyrow).FormatConditions.Count).SetFirstPriority
    With ws.Range(emptyrow).FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 5287936
        .TintAndShade = 0
    End With

I'm not sure exactly what you are doing. In particular, I'm not sure of the significance of this line,

ws.Range(emptyrow).FormatConditions(1).StopIfTrue = False   

especially when there are no conditional formats in the cell at the time it is executed.

But the following macro seems to do what yours would do if it were cleaned up a bit and written with proper syntax

Option Explicit
Sub highlightemptycell()
    Dim ws As Worksheet
    Dim r As Range
    Dim emptyrow As Long
    Dim err As Range

    Dim rEmptyRow As Range '<-- range object added to use below

    Set ws = Worksheets("Master")
    Set rEmptyRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Offset(rowoffset:=1)    '<<< safer....

With rEmptyRow.FormatConditions
    If .Count > 0 Then .Item(1).StopIfTrue = False
    .Add Type:=xlExpression, Formula1:= _
        "=ISBLANK(" & rEmptyRow.Address & ")"
        .Item(.Count).SetFirstPriority
    With .Item(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 5287936
        .TintAndShade = 0
    End With
End With
End Sub

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.

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