2012-11-06 109 views
5

我試圖將多個非連續區域的值複製到數組中。我寫這樣的代碼:excel vba如何將多個非連續區域的值複製到數組中

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

但它只複製第一部分(A2:D9)。然後,我嘗試了以下內容,並收到錯誤 - 「對象_全局失敗的方法聯合」 - 我使用聯合的方式有任何錯誤嗎?

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

只是使用split應用於範圍的地址,分隔符是「,」 –

回答

9

不知道發生了什麼事你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 
相關問題