根据其他单元格中的条件在相邻单元格中创建命名范围

时间:2019-07-16 11:54:09

标签: vba

我有以下代码...它应该遍历我的表,挑选出列B的值为“ OSI”,列C的值为“ Notifications”。有三行符合此条件。

由此,我想创建一个名为“ Notif”的命名范围,该范围跨越这些行从D到F的对应列,不包括B和C项。

@Override
    public void onTangoResponse(@NotNull Response<?> response) {
        boolean isSuccessful = response.isSuccessful();
        if (isSuccessful) { // code >= 200 && code < 300;
        } else {
            ErrorResponse errorResponse = getErrorResponse(response);
        }
}

运行上面的代码时,仅返回第一行,而不返回全部三行。我究竟做错了什么?我没有收到任何错误消息...

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

问题出在If cell.Value = "Notifications" And cell.Vaue = "OSI" Then中,因为cell.Value不能同时是“ Notifications”和“ OSI”。

此外,您只需要遍历范围的第一列,因此:For Each cell In notifRng.Columns(1).Cells

如果您检查是否分配了counter,则不需要rng变量。最后,在打印其地址-rng

之前,再次检查If Not rng Is Nothing Then Debug.Print rng.Address是一个好主意。

如果这是输入:

enter image description here

然后运行以下代码:

Sub TestMe()

    Dim sht As Worksheet
    Set sht = Worksheets(1)
    Dim notifRng As Range

    Set notifRng = sht.Range(sht.Range("B1"), sht.Range("C" & sht.Rows.Count).End(xlUp))
    Dim rng As Range

    Dim cell As Range
    For Each cell In notifRng.Columns(1).Cells
        If cell.Value = "OSI" And cell.Offset(columnoffset:=1).Value = "Notifications" Then
            If rng Is Nothing Then
                Set rng = sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))
            Else
                Set rng = Union(rng, sht.Range(cell.Offset(0, 1), cell.Offset(0, 3)))
            End If
        End If
    Next cell

    If Not rng Is Nothing Then Debug.Print rng.Address

End Sub

可以提供: $C$3:$E$3,$C$5:$E$5,$C$9:$E$9

答案 1 :(得分:0)

这可能对您有用。它不需要使用counter来查看范围是否已通过,而是检查Rng变量的状态。

Sub Test()

    Dim sht As Worksheet
    Dim NotifRng As Range
    Dim cell As Range
    Dim Rng As Range

    Set sht = ThisWorkbook.Worksheets("Sheet1")

    With sht
        Set NotifRng = .Range(.Cells(1, 2), .Cells(.Rows.Count, 2).End(xlUp))
    End With

    For Each cell In NotifRng 'loop through column B.
        If cell.Value = "Notifications" And cell.Offset(, 1) = "OSI" Then 'Check value in column B & C.
            If Rng Is Nothing Then 'If Rng doesn't contain a range then set one (columns C & E)
                Set Rng = sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))
            Else 'If Rng already contains a range(s) then add to it.
                Set Rng = Union(Rng, sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))) 'build the range
            End If
        End If
    Next cell

    ThisWorkbook.Names.Add "Notif", Rng

End Sub

嗯-尝试删除我的答案,因为@Vityata解释得更好,但这并不能阻止我。

相关问题