vba if语句错误

时间:2016-06-16 11:50:34

标签: excel vba excel-vba

您好我正在使用下面的代码,但是当我尝试一次从工作表中删除整个列(多个单元格)时显示错误。代码可以正常使用if语句,我只能删除所有" M" &安培; " I"工作表中的字符。 以下是代码:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Column = 18 Then
    ThisRow = Target.Row
    If Target.Value = "M" Then
        Range("AB" & ThisRow) = "NA"
    ElseIf Target.Value = "I" Then
     Range("AB" & ThisRow) = ""
    Else
    Range("AB" & ThisRow) = ""
    End If
    If Target.Value = "M" Then
        Range("AC" & ThisRow) = "NA"

    ElseIf Target.Value = "I" Then
     Range("AC" & ThisRow) = ""
    Else
    Range("AC" & ThisRow) = ""
    End If
        End If
End Sub

更新了代码

Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Integer, lastRow As Integer

If (Not Target.Column = 24) Then Exit Sub
If (Target.Columns.Count > 1) Then Exit Sub

lastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

Application.ScreenUpdating = False
For r = Target.Row To Target.Row + Target.Rows.Count - 1
    Range("Z" & r & ",AA" & r & ",AB" & r & ",AC" & r) = IIf(Cells(r, 24) = "Yes", "NA", "")
    Range("Y" & r & ",Z" & r & ",AA" & r & ",AB" & r & ",AC" & r & ",AD" & r) = IIf(Cells(r, 24) = "No", "NA", "")
    If (r = lastRow) Then Exit Sub
Next r
Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

通过在第一个If语句之前插入此行,可以在删除整个目标列时转义代码:

IIF

您还可以通过同时更新两个目标单元格并使用Private Sub Worksheet_Change(ByVal Target As Range) Dim r As Byte If (Target.Rows.Count > 1) Then Exit Sub If Target.Column = 18 Then r = Target.Row Range("AB" & r & ",AC" & r) = IIf(Target.Value = "M", "NA", "") End If End Sub 语句来计算值来简化代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim r As Integer, lastRow As Integer

    If (Not Target.Column = 18) Then Exit Sub
    If (Target.Columns.Count > 1) Then Exit Sub

    lastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

    Application.ScreenUpdating = False
    For r = Target.Row To Target.Row + Target.Rows.Count - 1
        Range("AB" & r & ",AC" & r) = IIf(Cells(r, 18) = "M", "NA", "")
        ' repeat above line for further checks
        Range("AE" & r & ",AF" & r) = IIf(Cells(r, 18) = "S", "NA", "")

        If (r = lastRow) Then Exit Sub
    Next r
    Application.ScreenUpdating = True
End Sub

更新以编辑多行:

x = tf.placeholder(tf.float32, shape=[None, 32,32,3])
y_ = tf.placeholder(tf.float32, shape=[None, 10])