2016-06-16 196 views
-1

嗨我正在處理下面的代碼,但它顯示錯誤,當我嘗試從工作表中一次刪除整個列(多個單元格)。該代碼與if語句正常工作,只是我不能從表單中一次刪除所有「M」&「我」字符。 下面是代碼:vba if語句錯誤

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 

末次

+1

什麼是拋出的錯誤,哪條線導致它? – RGA

+0

這條線('ElseIf Target.Value =「I」Then')沒有目的;你的代碼表明,如果目標單元格的值是M,則將AB/AC替換爲「NA」,否則將其替換爲「」。如果Else的輸出是同一個東西,那麼你不需要'ElseIf'。 – Dave

回答

1

您可以逃脫的代碼時,整個目標列由之前的第一如果在插入該行刪除聲明:

If (Target.Rows.Count > 1) Then Exit Sub 

您也可以同時更新兩種靶細胞和使用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 
+0

代碼工作正常,但是當我刪除像「M」這樣的值時,它也應該刪除已填充的單元格。意思是在刪除它所有填滿的單元格之後也應該是空白的。 – Striker

+0

我也可以知道是否需要添加一個除「M」之外的驗證,即不同單元格的「S」以突出顯示「不適用」我需要在上述代碼中做出哪些更改? – Striker

+0

我不太明白你的問題。這些不同的細胞是目標還是來源?如果要在列R包含值「S」時創建單獨的列表(即不同的目標),則將第一行復制到For循環中,之後立即插入並更新值。如果您希望輸出在同一個列表中,您可以將新條件添加到IIF條件中,例如'IIf(Cells(r,18)=「M」或Cells(r,18)=「S」 NA「,」「)'。 – lonestorm