相信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
只是使用split應用於範圍的地址,分隔符是「,」 –