2016-11-21 50 views
0

我有一個列表 - 這是我剛剛發現這個語法,將允許多選擇從我的名單:檢查數組在VBA

Dim Oldvalue As String 
Dim Newvalue As String 

On Error GoTo Exitsub 
If Target.Address = "$B$1" Then 
    If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then 
    GoTo Exitsub 
    Else: If Target.Value = "" Then GoTo Exitsub Else 
    Application.EnableEvents = False 
    Newvalue = Target.Value 
    Application.Undo 
    Oldvalue = Target.Value 
    If Oldvalue = "" Then 
     Target.Value = Newvalue 
    Else 
     Target.Value = Oldvalue & ", " & Newvalue 
    End If 
    End If 
End If 
Application.EnableEvents = True 

Exitsub: 
Application.EnableEvents = True 

我可以告訴大家,選擇值的列表將被存儲在可變Target.Value - 但我怎麼:

1)檢查Target.Value(這樣的長度,我知道如果我選擇1或多層)

2)遍歷每個選擇?

+0

您的GoTo Exitsub都可以用'Exit'替換。 – Andreas

+0

你的意思是你想要一個數字值的字符串的長度? 'Len(target.value)' – Andreas

+0

@Andreas - 讓我們說列表值是紅色,綠色,藍色 - 我需要一種方法來知道選擇了什麼東西像foeach(在Target.Value中選擇字符串)msgBox.Show(pick)下一個 –

回答

1

您需要將Target.Value分配給Variant變量。請記住在變量名後加括號,表示您正在分配一個數組。

然後,您可以使用LBoundUBound找到數組的維數,也可以遍歷數組。很確定這是你想要做的。

Sub get_vals() 

    Dim arr() As Variant 
    Dim i As Long 

    arr = Range("A1:A5").Value 

    Debug.Print UBound(arr, 1) ' Print rows 
    Debug.Print UBound(arr, 2) ' Print columns 

    For i = LBound(arr, 1) To UBound(arr, 1) ' Iterate through the rows of the array 

     Debug.Print arr(i, 1) 

    Next i 

End Sub 

編輯

隨着長大,你將不能夠到一個單元格範圍分配給數組變量。你不妨使用Dim arr As Variant。這將允許您將一個單元格區域分配給該變量。然後,您可以檢查類型以確定是否需要迭代數組或僅使用單個字符串/整數。

If TypeName(arr) = "Variant()" Then 
    ' Iterate 
Else 
    ' Work with single string/integer 
End If 
+0

這個解決方案有一個警告:如果目標範圍只有一個單元格,你會得到一個類型不匹配,因爲'.Value'將返回一個變體而不是變體數組。根據應用程序,可能需要檢查範圍是否首先包含多個單元格。 – arcadeprecinct

+0

非常真實,@arcadeprecinct。在分配變量之前需要進行檢查。 –

2

沒有設定陣列可以使用

Target.Rows.Count 'number of rows 
Target.Columns.Count 'number of columns 
Target.Cells.Count 'number of cells 

您可以通過他們使用指數環或

Dim cl As Range 
For Each cl In Target.Cells 'For Each loops are much faster then looping using indices 
    'do something with cl 
Next cl 

還要注意托馬斯Inzina的評論,這種方式,您將得到所有的細胞即使你有一個不連續的範圍。

編輯:For Each環路更快,使用指數,即

For i = 1 To Target.Rows.Count 
    For j = 1 To Target.Columns.Count 
     'do something with Target.Cells(i, j) 
    Next j 
Next i 

使用數組作爲luke_t建議通過細胞循環可能甚至更快。

+0

如果您將蘋果與蘋果進行比較,則每個循環比使用索引要快得多。 luke_t正在使用一組值,其中當您正在迭代單元格時。我的猜測是陣列會更快。但是,你有正確的答案。1)如果目標是非連續的範圍,那麼只有範圍的第一個區域將被複制到數組中。 2)直接使用單元格更直觀,而不必編輯數組並將其複製回來。 +1 – 2016-11-21 13:30:14

+0

@ThomasInzina是的,我應該指定它比使用索引循環單元格更快。 – arcadeprecinct