excel vba范围偏移范围相对

时间:2016-11-03 20:22:23

标签: excel vba excel-vba

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

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

我的目标是查看某个地区的所有细胞。如果当前单元格为空并且左边的单元格的数值为0,那么我想输入文本" 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

任何指导都将不胜感激。

2 个答案:

答案 0 :(得分:1)

我会测试目标的细胞是否在Range("B1:M1000")中。从Worksheet_Change事件更改ActiveSheet上的值时,应始终关闭事件。

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

答案 1 :(得分:1)

我走这条路

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
相关问题