如何在VBA中获取数组中项目的范围地址?

时间:2014-02-18 10:43:11

标签: excel vba

Sub sel_to_array()

    Dim arr As Variant
    Dim i

    Sheets("Ps").Activate
    Sheets("Ps").Range("C6").Select
    Range(Selection, Selection.End(xlDown)).Select

    'arr = ActiveCell.CurrentRegion.Value
    arr = Selection

    For Each i In arr
        MsgBox i

        If Round(i, 0) = Round(proj_cbox.Value, 0) Then
            GoTo 1:
        End If

        Next i

End Sub

以下是它的作用:当它找到相等的匹配时,我想知道它的单元格位置是什么,例如A3A13

3 个答案:

答案 0 :(得分:2)

试试这个

Sub sel_to_array()

    Dim arr As Range, rng As Range, cell As Range
    Dim lastRow As Long

    Sheets("Ps").Activate
    lastRow = Sheets("Ps").Range("C" & Rows.Count).End(xlUp).Row

    If lastRow <= 5 Then Exit Sub

    Set rng = Range("C6:C" & lastRow)

    For Each cell In rng
        If Round(cell.Value, 0) = Round(proj_cbox.Value, 0) Then
            MsgBox cell.Address
        End If
    Next

End Sub

答案 1 :(得分:1)

不确定为什么要将范围弹回到数组。如果不是真的需要你可以试试这个:

Sub sel_to_address()
  Dim MyRange As Range
  For Each MyRange In Range(Sheets("Ps").Range("C6"), Sheets("Ps").Range("C6").End(xlDown))
    MsgBox MyRange.Value
    If Round(MyRange.Value, 0) = Round(proj_cbox.Value, 0) Then
      MsgBox MyRange.Address
    End If
  Next MyRange
End Sub

答案 2 :(得分:0)

尝试:

MsgBox i.Address

或者你可以这样做

Set arr = Selection 'set here forces arr to a range object

If Round(i, 0) = Round(proj_cbox.Value, 0) Then
    With i.Interior
        .Pattern = xlSolid
        .ColorIndex = 36 'Light Yellow
    End With
Else
    i.Interior.ColorIndex = xlNone
End If

将使用与该值匹配的淡黄色对所有细胞进行着色,并清除所有不具有该值的细胞的阴影。