循环范围

时间:2015-10-12 23:30:12

标签: excel vba excel-vba

我有一个通过或未通过验证(BA)的单元格。如果用户从下拉列表中选择Pass,则unit passed all tests将显示在另一个单元格(N)中。我用来实现这一目标的VBA按预期工作:

在Worksheet_Change

If Range("BA17").Value = "Pass" Then Range("N44").Value = "Unit passed all tests."
If Range("BA18").Value = "Pass" Then Range("N45").Value = "Unit passed all tests."
If Range("BA19").Value = "Pass" Then Range("N46").Value = "Unit passed all tests."  

是否有可能将其浓缩,因为最终的纸张最多会有25-30行?

我尝试添加一个范围,即(" BA17:BA40")但是每次都会更新所有字段,这是不理想的。

2 个答案:

答案 0 :(得分:1)

这将使用值&#34更新列N(行偏移27);单元通过所有测试。"如果仅更新列BA中的一个单元并且当前行> 17

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    With Target
        If .CountLarge = 1 And .Column = Range("BA1").Column And .Row > 17 Then
            If .Value2 = "Pass" Then
                Application.EnableEvents = False
                .Offset(27, Range("N1").Column - .Column).Value = "Unit passed all tests."
                Application.EnableEvents = True
            End If
        End If
    End With

End Sub

答案 1 :(得分:0)

避免多个条目循环的选项

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rng1 As Range
Set rng1 = Intersect(Target, [BA17:BA40])
If rng1 Is Nothing Then Exit Sub

Application.EnableEvents = False
With rng1.Offset(27, -39)
        .FormulaR1C1 = "=IF(R[-27]C[39]=""Pass"",""Unit passed all tests."","""")"
        .Value = .Value
End With
Application.EnableEvents = True

End Sub