2017-04-12 54 views
1

我具有存儲在其單元的地址和範圍可變型變種一個dimenaional陣列的元件地址如何地址範圍refrence分成

例如:

Dim cells_addresses as variant 
Cells_addresses="$A$1,$C$3:$F$3,$F$4" 

現在我想使用拆分功能或在VBA任何其他子或功能,以一個維陣列分裂的那些細胞的地址如下所示:

Output_Array="$A$1","$C$3","$D$3","$E$3","$F$3","$F$4" 

任何人有一個想法如何地址範圍分成逐張數組的一個元素?

+0

你可以簡單地通過所有這些循環使用'對於Range中的每個單元格(Split(Cells_addresses,「,」)(1))'(或類似的東西)。 – Ralph

+0

@walid attia您是否嘗試過下面提供的任何解決方案?任何反饋 ? –

+0

我還沒試試。我有一些身體上的麻煩。我會明天嘗試,因爲我感覺好多了。但是真的,我很欣賞你們的偉大答案.thanks slot。 –

回答

0

或者這樣......

Dim cells_addresses As Variant 
Dim OutputArr() 
Dim cell As Range 
Dim str() As String 
Dim i As Long, ii As Long 
cells_addresses = "$A$1,$C$3:$F$3,$F$4" 
str() = Split(cells_addresses, ",") 
For i = 0 To UBound(str) 
    For Each cell In Range(str(i)) 
     ii = ii + 1 
     ReDim Preserve OutputArr(1 To ii) 
     OutputArr(ii) = cell.Address 
    Next cell 
Next i 
MsgBox Join(OutputArr, ", ") 
+0

你提供的代碼工作得很好。謝謝 –

+0

不客氣Walid!很高興它的工作。請花點時間接受答案,將您的問題標記爲已解決。 – sktneer

1

這裏有一種方法:

Function SplitRanges(RangeString As Variant) As Variant 
    Dim ranges As Variant, v As Variant 
    Dim c As Range 
    Dim i As Long, j As Long, n As Long 
    ranges = Split(RangeString, ",") 
    For i = 0 To UBound(ranges) 
     n = n + Range(ranges(i)).Cells.Count 
    Next i 
    ReDim v(1 To n) 
    i = 0 
    For j = 0 To UBound(ranges) 
     For Each c In Range(ranges(j)).Cells 
      i = i + 1 
      v(i) = c.Address 
     Next c 
    Next j 
    SplitRanges = v 
End Function 

測試,如:

Sub test() 
    Dim s As String 
    s = "$A$1,$C$3:$F$3,$F$4" 
    Debug.Print Join(SplitRanges(s), ",") 
End Sub 

輸出:

$A$1,$C$3,$D$3,$E$3,$F$3,$F$4 
+0

既然你是這裏唯一的純數學家,你知道如何基於你的解決方案性能與我的基準嗎?越快越好+1 :) –

+0

@ShaiRado VBA是一個基準測試的痛點,現在我必須在今天晚些時候爲一個類的功率點演示工作。我懷疑當單元的數量<= 1000時,你的方法會更快,因爲我通過額外的數據傳遞來預先分配數組並且對Range()有更多的調用。像你一樣使用'Range()'調用一個聰明的方法。 –

+0

發給我PowerPoint,我對這些很滿意;) –

2

您可以使用您提供的Cells_addresses值來設置Range。之後,循環遍歷Range.Areas,並嵌套在每個Area單元格下面的循環中,並且每個單元格添加到您的Output_Array

代碼

Option Explicit 

Sub SplitRangeAddrrtoArray() 

Dim cells_addresses As Variant 
Dim UnionRng As Range 
Dim RngArea As Range 
Dim C As Range 
Dim i As Long 
Dim Output_Array() As Variant 

cells_addresses = "$A$1,$C$3:$F$3,$F$4" 
ReDim Output_Array(0 To 1000) ' init array size >> will optimize later 

Set UnionRng = Range(cells_addresses) '<-- Set a Range with the cells addresses provided 
' loop through range's areas in case there are multiple areas 
For Each RngArea In UnionRng.Areas 
    For Each C In RngArea ' loop through the area's cells 
     Output_Array(i) = C.Address 
     i = i + 1 
    Next C 
Next RngArea 
ReDim Preserve Output_Array(0 To i - 1) '<-- resize to actual populated size 

End Sub 
+0

@ shai重做。它工作的非常好。謝謝很多 –

+0

重做它很好地與我.thanks插槽的代碼是完美 –

+0

重做,我不知道如何 –

0

沒有儘快possible.you是偉大的球員嘗試解答。但我會給我的反饋