查找范围地址

时间:2017-12-04 14:42:57

标签: excel vba

我想根据单元格值选择一些范围,因为它们可能每次都在不同的列中。

所以我的第一个想法是下面的东西,但我不确定这是不是正确的方法?

Sub RangeBetween()

Dim rng1 As Range, rng2 As Range
Dim totalRange As Range
Dim c1, c2 As Integer

c1 = 1
    Do Until Name = "A"
        Name = Cells(1, c1)
        c1 = c1 + 1
    Loop
someA= c1 - 1

c2 = 1
    Do Until Name = "B"
        Name = Cells(1, c2)
        c2 = c2 + 1
    Loop
someB= c2 - 1

Set rng1 = Range("???")
Set rng2 = Range("???")

Set totalRange = Range(rng1.Address & ":" & rng2.Address)
    totalRange .Select
    End Sub

由于

1 个答案:

答案 0 :(得分:3)

或者您可以使用Match()

Sub RangeBetween()


Dim totalRange As Range
Dim c1 As Long, c2 As Long


c1 = 0
c2 = 0
With Worksheets("Sheet1") 'Change to your worksheet
    On Error Resume Next
        c1 = Application.WorksheetFunction.Match("A", .Rows(1), 0)
        c2 = Application.WorksheetFunction.Match("B", .Rows(1), 0)
    On Error GoTo 0

    If c1 > 0 And c2 > 0 Then
        Set totalRange = .Range(.Cells(1, c1), .Cells(1, c2))
        totalRange.Select
    Else
        MsgBox "One or both items not found in range"
    End If
End With

End Sub