我正在尝试使用 B6:B183 范围内的非空单元格中的值创建数组。 array_articles = ActiveWorsheet.Range("B6:B183")
返回空数组,所以我正在尝试这样做:
Sub set_price()
Dim articul_price() As String
Dim articul_bill As String
Dim counter As Integer
Dim array_articles() As Variant
Dim array_unsorted() As String
Dim cell As Range
counter = 0
ReDim articul_price(0)
For Each cell In ActiveWorsheet.Range("B6:B183") ' error 424 Object required
If IsEmpty(cell.Value) Then
array_unsorted(counter) = cell.Value
ReDim Preserve array_unsorted(counter)
Else
'do nothing
counter = counter + 1
End If
Next
End Sub
此代码返回
error 424 Object required
最佳答案
要轻松地将范围加载到数组中(没有循环),请使用:
Dim array_unsorted As Variant 'must be variant!
array_unsorted = ThisWorkbook.Worksheets("NameOfSheet").Range("B6:B183").Value '2-dimensional array
您可以使用
Debug.Print array_unsorted(row, column) 'yes it has only 1 column but it is still there
Debug.Print array_unsorted(1, 1) 'first value
Debug.Print array_unsorted(2, 1) 'second value
或将其转置以使其成为一维
array_unsorted = WorksheetFunction.Transpose(ThisWorkbook.Worksheets("NameOfSheet").Range("B6:B183").Value) '1-dimensional
你可以访问数组
Debug.Print array_unsorted(i) 'this is 1-dimensional
Debug.Print array_unsorted(1) 'first value
Debug.Print array_unsorted(2) 'second value
请注意,转置函数的限制为 65,536 行。如果超过它们,其余部分将被静默截断。
我建议避免使用
ActiveWorksheet
(除非您编写加载项或代码用于多个工作表)。使用ThisWorkbook.Worksheets("NameOfSheet")
按名称引用工作表,这样更节省,Excel 不会出错。
关于excel - 我正在尝试使用来自事件表(VBA)的值创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53408372/