excel vba如何将多个非连续范围的值复制到数组中

问题描述 投票:6回答:3

我试图将多个非连续范围的值复制到一个数组中。我写了这样的代码:

summaryTempArray = .range("A2:D9,A11:D12,A14:D15").Value

但它只复制第一部分(A2:D9)。然后,我尝试了以下内容,我得到了错误 - “对象_全局失败的方法联盟” - 我使用联合的方式有什么错误吗?

summaryTempArray = Union(.range("A2:D9"), .range("A11:D12"), .range("A14:D15")).Value
excel-vba vba excel
3个回答
10
投票

不知道你的union有什么问题,但它会产生相同的范围,你在第一次尝试中就说过了。

问题是,你现在有多个领域。你可以,据我所知,你现在必须解决这个问题。

下面是一个示例,它将在所有区域的数组中解析,而无需单独添加每个单元格,而是将每个区域单独添加到摘要数组中:

Public Sub demo()
  Dim summaryTempArray() As Variant
  Dim i As Long

  With Tabelle1
    ReDim summaryTempArray(1 To .Range("A2:D9,A11:D12,A14:D15").Areas.Count)

    For i = 1 To .Range("A2:D9,A11:D12,A14:D15").Areas.Count
      summaryTempArray(i) = .Range("A2:D9,A11:D12,A14:D15").Areas(i)
    Next i
  End With

End Sub

希望这可以帮助。


2
投票

我相信,如果将源范围放入数组很重要,那么Jook的解决方案就像您将要获得的一样好。但是,我认为解决方案应包括从不规则数组中提取值的说明。这并不难,但语法模糊不清。

我无法让你的Union声明失败。我假设有一些关于导致失败的上下文,我无法复制。

下面的代码显示两个范围相同,并且只有第一个子范围被加载到您报告的数组。它完成了另一种可能令人满意的方法。

Option Explicit
Sub Test()

  Dim CellValue() As Variant
  Dim rng As Range

  With Worksheets("Sheet1")

    Set rng = .Range("A2:D9,A11:D12,A14:D15")
    Debug.Print rng.Address
    Set rng = Union(.Range("A2:D9"), .Range("A11:D12"), .Range("A14:D15"))
    Debug.Print rng.Address
    ' The above debug statements show the two ranges are the same.

    Debug.Print "Row count " & rng.Rows.Count
    Debug.Print "Col count " & rng.Columns.Count
    ' These debug statements show that only the first sub-range is included the
    ' range counts.

    CellValue = rng.Value

    Debug.Print "Rows " & LBound(CellValue, 1) & " to " & UBound(CellValue, 1)
    Debug.Print "Cols " & LBound(CellValue, 2) & " to " & UBound(CellValue, 2)
    ' As you reported only the first range is copied to the array.

    rng.Copy Destination:=Worksheets("Sheet2").Range("A1")
    ' This shows you can copy the selected sub-ranges.  If you can copy the
    ' required data straight to the desired destination, this might be a
    ' solution.

  End With

End Sub

0
投票

我遇到了同样的问题并尝试了一些方法但没有成功,直到我点击这个: -

    dim i as integer
    Dim rng1 as range
    Dim str as string
    dim cels() as string
    Set rng1 = sheet1.Range("A2:D9,A11:D12,A14:D15")
    str = rng1.address(0,0)
    cels() = split(str, ",")     '<--- seems to work OK
    for i = 0 to 2
        Debug.Print cels(i)
    Next i             

如果这是一个“不正确”的转换方法,我会感兴趣。

© www.soinside.com 2019 - 2024. All rights reserved.