IF范围不返回所需的值

时间:2018-02-08 16:03:12

标签: excel vba excel-vba

我遇到一个问题,我不明白如何修复它。这是一个简单的代码:如果范围(“A1:A100”)=“产品”,则范围(“B1:B100”)应自动为1(此范围为空)。例如:如果有人写入 A1 =产品,那么 B1 应自动拥有 1 。否则,如果从 A1 中删除产品,则应从 B1 中删除 1 。我的代码如下:

提前致谢!

Sub product(o As Long)

If Cells(o, "A") = "Product" And Cells(o, "B") = "" Then
    Cells(o, "B") = "1"
ElseIf Cells(o, "A") = "" And Cells(o, "B") = "1" Then
    Cells(o, "B") = ""

End If

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)


Dim cell As Range
Dim cell1 As Range
Set cell = Intersect(Range("b1:b100"), Target)
If Not cell Is Nothing Then
    For Each cell1 In cell.Rows
        product cell1.Row
    Next cell1
End If


End Sub

2 个答案:

答案 0 :(得分:1)

实际上只需要一个小修复:

Set cell = Intersect(Range("A1:B100"), Target)

而不是b1:b100。如果您想让整个列保持活动状态,您甚至可以考虑Range("A:B")

答案 1 :(得分:1)

在工作表的代码表中,

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Not Intersect(Columns(1), Target) Is Nothing Then
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Dim trgt As Range
        For Each trgt In Intersect(Columns(1), Target, Target.Parent.UsedRange)
            Select Case LCase(trgt.Value2)
                Case "product"
                    trgt.Offset(0, 1) = 1
                Case ""
                    trgt.Offset(0, 1) = vbnullstring
                Case Else
                    'do nothing
            End Select
        Next trgt
    End If
safe_exit:
    Application.EnableEvents = True

End Sub