工作表更改 - 无法定位不同的行

时间:2016-11-02 15:39:01

标签: vba excel-vba excel

我刚刚开始使用VBA并学习了如何使用更改事件处理程序更改列 - 但是当我还需要更改行时,我无法使其工作。基于一个单元格中的响应,即"是"或"否" - 我想用" N / A"填充其他单元格。或空白。

我已经让它连续工作但我现在需要把#34; N / A"在其他行上也是如此。请有人帮忙。我的代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target, Range("I6:I7")) Is Nothing Then
    If Cells(Target.Row, 9) = "Manual" Then
      Cells(Target.Row, 10) = "N/A"
      Cells(Target.Row, 11) = "N/A"
      '**Cells(8, 11) = "N/A"**
    ElseIf Cells(Target.Row, 9) = "Depalletiser" Then
      Cells(Target.Row, 10) = ""
      Cells(Target.Row, 11) = ""
    ElseIf Cells(Target.Row, 9) = "Robot" Then
      Cells(Target.Row, 10) = ""
      Cells(Target.Row, 11) = ""
    End If
  End If
End Sub

2 个答案:

答案 0 :(得分:0)

您可以使用偏移

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Cells(Target.Row, Target.Column).Offset(rowOffset:=3, columnOffset:=0) _
.Value = "I'm beneath you  :-o"
Columns(Target.Column).AutoFit
End Sub

答案 1 :(得分:0)

总结你已经收到的建议和评论,并提出一些新的观点,你可以考虑这个代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("I6:I7")) Is Nothing Then
        Application.EnableEvents = False '<-- best practice: avoid subsequent possible worksheet changes trigger this event again and again in an infinite loop
        On Error GoTo ExitSub '<--best practice: be sure to get and enable events should any error cause the end of this sub

        Select Case Cells(Target.Row, 9).Value
            Case "Manual"
                Target.Offset(, 1).Resize(, 2) = "N/A"
            Case "Depalletiser", "Robot"
                Target.Offset(, 1).Resize(, 2).ClearContents
        End Select
    End If

ExitSub:
    Application.EnableEvents = True
End Sub