excel - 我正在尝试使用来自事件表(VBA)的值创建数组

标签 excel vba

我正在尝试使用 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



In Locals

最佳答案

要轻松地将范围加载到数组中(没有循环),请使用:

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/

相关文章:

java - Jexcel公式计算错误

vba - 如何限制表单字段的字符数

vba - Excel 宏 - 选择所有包含数据和格式为表格的单元格

vba - 使 MS Access 中的查询在打印时默认为横向

excel - 如何让 VBA excel 插件 .xlam 用远程更新的 .xlam 替换自身?

vba - Excel VBA 运行时错误 '-2147319767 (80028029)'

excel - 尝试将超过 4000 条记录导出到 excel 时,Telerik Kendo 网格导出到 excel 没有响应

arrays - 在 VBA Excel 中重用二维数组?

excel - 如何访问嵌套字典的键?

vba - 如果正在使用工作簿,请引用打开工作簿并创建错误消息