excel vba范围偏移范围相对

我正在尝试在工作表中格式化一个区域。

我正在使用Worksheet_Change,以便它始终更新更改。

我的目标是看一个地区的所有细胞。 如果当前单元格为空,而左边的单元格的数值为0,那么我想在当前单元格中input文本“N / A”。

我的尝试失败,因为偏移不能使用。

Private Sub Worksheet_Change(ByVal Target As Range) Dim updateCells As Range Dim myCell As Range Set updateCells = Range("B1:M1000") For Each myCell In updateCells ' NEXT LINE WRONG!! If myCell.Offset(0, -1).Value = 0 Then myCell.Interior.ColorIndex = 4 End If Next End Sub 

任何指导将不胜感激。

我会testing目标的单元格是否在Range("B1:M1000") 。 从Worksheet_Change事件更改ActiveSheet上的值时,应始终closures事件。

 Private Sub Worksheet_Change(ByVal Target As Range) Application.EnableEvents = False Dim r As Range For Each r In Target.Cells If Not Intersect(r, Range("B1:M1000")) Is Nothing Then If r.Value = "" And Not r.Offset(0, -1).Value = "" And r.Offset(0, -1).Value = 0 Then r.Value = "N\A" r.Interior.ColorIndex = 4 Else r.Interior.ColorIndex = -4142 End If Next Application.EnableEvents = True End Sub 

我会走这条路

 Private Sub Worksheet_Change(ByVal Target As Range) Dim rng As Range, myRng As Range On Error GoTo ExitSub '<--| be sure to exit sub in a managed way and restore events handling Set myRng = Intersect(Target, Range("B1:M1000")).SpecialCells(xlCellTypeBlanks) '<--| get blank changed cells belonging to relevant range Application.EnableEvents = False '<--| turn rvents handling ofF For Each rng In myRng '<--| loop through filtered range only If Not rng.Offset(0, -1).Value = "" And rng.Offset(0, -1).Value = 0 Then rng.Value = "N\A" rng.Interior.ColorIndex = 4 Else rng.Interior.ColorIndex = -4142 End If Next ExitSub: Application.EnableEvents = True '<--| turn events handling on End Sub