【问题标题】:Type mismatch in VBA when trying to set array values尝试设置数组值时在 VBA 中键入不匹配
【发布时间】:2020-07-01 14:25:00
【问题描述】:

我正在尝试从 AutoCAD 导出并生成材料清单 (BOM)。输出文件对放置在模型中的每个项目都有一个条目(由于情有可原的情况,我不能使用 AutoCAD 的内置 BOM 构建功能)。制作 BOM 时,我需要没有重复的零件编号和总数量。

首先,我将所有零件编号添加到一个数组中。然后我使用了一个函数(我没有写)来删除重复项。然后我尝试将我的原始零件编号数组重新调整为 2D 和无重复数组的长度。接下来,我想将无重复数组中的所有值添加回第一列中的原始数组。后来我知道了如何对零件编号求和并将它们与匹配的零件编号一起添加到数组的第二列。

这里是我给出的一个例子:

CPN:   QTY:
5551    1
5552    3
5551    1
5551    1
5555    6

这是我需要的输出(排序无关紧要)

CPN:    QTY:
5551     3
5552     3
5555     6

这是我目前拥有的完整代码。我在cpns(i, 1) = temp(i) 收到错误

Sub consolidate()

Dim arrfirst As Integer, arrlast As Integer
Dim cpns() As Variant
Dim CPN_COUNT As Integer

Range("E1000").Select
Selection.End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Range("E2:E4").Select
Range("E4").Activate
CPN_COUNT = Selection.Count
ReDim cpns(1 To CPN_COUNT)


For i = 1 To CPN_COUNT
    cpns(i) = Cells(i + 1, 5)
Next

temp = ArrayRemoveDups(cpns)
arrfirst = LBound(temp)
arrlast = UBound(temp)
ReDim cpns(arrfirst To arrlast, arrfirst To arrlast)

For Each i In temp
    cpns(i, 1) = temp(i)
Next


End Sub


Function ArrayRemoveDups(MyArray As Variant) As Variant
    Dim nFirst As Long, nLast As Long, i As Long
    Dim item As String
    
    Dim arrTemp() As String
    Dim Coll As New Collection
 
    'Get First and Last Array Positions
    nFirst = LBound(MyArray)
    nLast = UBound(MyArray)
    ReDim arrTemp(nFirst To nLast)
 
    'Convert Array to String
    For i = nFirst To nLast
        arrTemp(i) = CStr(MyArray(i))
    Next i
    
    'Populate Temporary Collection
    On Error Resume Next
    For i = nFirst To nLast
        Coll.Add arrTemp(i), arrTemp(i)
    Next i
    Err.Clear
    On Error GoTo 0
 
    'Resize Array
    nLast = Coll.Count + nFirst - 1
    ReDim arrTemp(nFirst To nLast)
    
    'Populate Array
    For i = nFirst To nLast
        arrTemp(i) = Coll(i)
    Next i
    
    'Output Array
    ArrayRemoveDups = arrTemp
 
End Function

感谢任何帮助。我确信有一种更简单的方法可以完成所有这些操作,但我是 VBA 新手

我还应该在我的错误点添加 cpns 的数据类型是 Variant/Variant,而 temp 的数据类型是 Variant/String。

【问题讨论】:

  • cpns 是一维数组,不是二维数组。
  • ReDim cpns(arrfirst To arrlast, arrfirst To arrlast) 不会重新定义为 2D 吗?
  • 对不起,我错过了第二个ReDim。两个ReDims 有点危险。肯定有更好的方法...等一下。
  • 第一个redim只是将它的初始大小设置为数据的大小。第二个是将其重置为新数据的大小(删除重复项)并添加第二个维度,我可以在其中存储数量值。
  • 数组应该像For i = Lbound(temp) to Ubound(temp)那样迭代,而不是For Each

标签: arrays excel vba type-mismatch


【解决方案1】:

数组应该使用For i = Lbound(...) to Ubound(...)进行迭代,而不是For Each

改变

For Each i In temp

For i = Lbound(temp) to Ubound(temp)

正如 cmets 中所指出的,您可以使用 For Each 循环...但是不要

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多