2014-04-18 25 views
1

用戶必須選擇一列數據,然後在我的vba代碼中使用數組。如果用戶選擇列字母,他會得到整列,數據和空白單元格。有沒有辦法,除了通過數組,一次一個項目,獲取該列中的數據,當選擇整個列時。僅獲取選定列範圍的數據

我有這樣的代碼:

Set user_range = ActiveWindow.RangeSelection 
points = user_range.value 

i = LBound(points, 1) 

count = UBound(points, 1) - i + 1 

我感謝所有幫助任何人都可以給!

感謝,

拉斯

回答

1

這是可能的背景。

1)如果Selection可以包含僅常數

Dim user_range As Range 
Dim points 
On Error Resume Next 
Set user_range = Selection.SpecialCells(xlCellTypeConstants) 
On Error GoTo 0 
If Not user_range Is Nothing Then points = user_range.Value 

2)如果Selection可以包含僅各式中

Dim user_range As Range 
Dim points 
On Error Resume Next 
Set user_range = Selection.SpecialCells(xlCellTypeFormulas) 
On Error GoTo 0 
If Not user_range Is Nothing Then points = user_range.Value 

3)如果Selection可能包含常量和公式

Dim rng1 As Range, rng2 As Range, user_range As Range 
Dim points 

On Error Resume Next 
Set rng1 = Selection.SpecialCells(xlCellTypeConstants) 
Set rng2 = Selection.SpecialCells(xlCellTypeFormulas) 
On Error GoTo 0 

If Not rng1 Is Nothing And Not rng2 Is Nothing Then 
    Set user_range = Union(rng1, rng2) 
ElseIf Not rng1 Is Nothing Then 
    Set user_range = rng1 
ElseIf Not rng2 Is Nothing Then 
    Set user_range = rng2 
End If 

If Not user_range Is Nothing Then points = user_range.Value 

4),如果你想減少選擇的未使用部分(這是從來沒有使用的部分) ,你可以嘗試下面的代碼(但在很多情況下,它是不可靠的,因爲UsedRange包含至少一次使用過的所有單元格,例如如果刪除單元格中的值,則此單元格將爲空,但仍爲UsedRange的一部分):

Dim user_range As Range 

Set user_range = Intersect(UsedRange, Selection) 
If Not user_range Is Nothing Then points = user_range.Value 
+1

很好的答案!...................... –