将相邻范围添加到现有范围

时间:2014-08-06 09:29:38

标签: excel vba excel-vba

我有一个相当不寻常的问题

我试图创建一个包含多个区域的命名区域。 使用它我将使用索引中的[area]方法来检索我的数据

我要做的是在Excel中引用一个指定范围,引用几个区域

MyNamedRange referto =" A1:A3,B1:B3,C1:C3"等

这个命名范围是用VBA构建的,所以我拥有的是

For x = 1 to 10
   Set rngTemp = Range(cells(x,1), cells(x,3))
    if x > 1 then       
      Set unionRange = union(unionRange, rngTemp)
    else
      Set unionRange = rngTemp
    end if
Next x

MyWorkBook.Names.Add Name:="MyRange", RefersTo:=unionRange

但是,此范围设置为A1:C3(因此不分为几个区域)

我知道这是因为范围彼此相邻,但无论如何我可以覆盖它并确保Excel将它们分成几个区域?

致以最诚挚的问候,

1 个答案:

答案 0 :(得分:0)

这是你在尝试的吗?

Sub Sample()
    Dim MyWorkBook As Workbook
    Dim ws As Worksheet
    Dim x As Long
    Dim rngTemp As Range
    Dim refR1C1 As String

    '~~> Change this to the relevant workbook
    Set MyWorkBook = ThisWorkbook

    '~~> Change this to the relevant Sheet
    Set ws = MyWorkBook.Sheets("Sheet1")

    With ws
        For x = 1 To 10
            Set rngTemp = Range(.Cells(x, 1), .Cells(x, 3))

            If refR1C1 = "" Then
                refR1C1 = "="
            Else
                refR1C1 = refR1C1 & .Name & "!" & rngTemp.Address(ReferenceStyle:=xlR1C1) & ","
            End If
        Next x

        refR1C1 = Left(refR1C1, Len(refR1C1) - 1)
    End With

    Debug.Print refR1C1

    MyWorkBook.Names.Add Name:="MyRange", RefersToR1C1:=refR1C1

    Debug.Print Range("MyRange").Areas.Count
End Sub

<强>截图

enter image description here