检查Value是否在数组中,以及是否未将其添加到末尾

时间:2018-12-26 17:16:38

标签: arrays vba

我正在尝试创建一个仅包含唯一值(信号名称)的数组。例如我的电子表格看起来像这样

电压 电压 电压 当前 当前 当前 等等...

但是我有32个信号,即使我不知道我有32个信号(即17个信号),我也希望它能正常工作。

Signals(“ Voltage”,“ Current”,“ Etc ....”)

在下面的代码中

我意识到我正在尝试在循环中重新创建数组,这就是问题所在。我只是无法想到另一种方法。我宁愿暂时将其保留为数组问题,而不是字典或集合问题。

Public Sub Signals()

Dim myArray() As Variant
Dim Signals() As Variant
Dim element As Variant
Dim intA As Integer

WsName = ActiveSheet.Name

intRows = Sheets(WsName).Range("B2", Sheets(WsName).Range("B" & Sheets(WsName).Rows.Count).End(xlUp)).Rows.Count
intRows = intRows + 1

ReDim Signals(1)
Signals(1) = Sheets(WsName).Cells(4, 2).Value

For intA = 4 To intRows
    For Each element In Signals()
        If element <> Sheets(WsName).Cells(intA, 2) Then
            ReDim Signals(UBound(Signals) + 1) 'This throws the error
            Signals(UBound(Signals)) = Sheets(WsName).Cells(intA, 2).Value
        End If
    Next element
Next


End Sub

代码不起作用-运行时错误'10'数组被临时固定或锁定。

2 个答案:

答案 0 :(得分:2)

几天前,我在一个类似的问题中使用数组发布了此问题的解决方案-使用B列来解决这个问题。

除此解决方案外,您当前的代码中还有几个问题-您正在对当前数组中的每个元素进行测试,而没有先检查所有元素,还没有使用ReDim Preserve,并且您需要{ {1}},而不仅仅是单个(0 to 0)(0)。您还试图在子例程中声明变量“ Signals”时,也在命名子例程“ Signals”……这会引起各种问题。

(1)

由于@ user10829321的建议,甚至更简单的解决方案:

Sub Test()

Dim list() As Variant
Dim inlist As Boolean
Dim n As Long, i As Long, j As Long, endrow As Long, colnum As Long

ReDim list(0 To 0)
inlist = False
j = 0
colnum = 2 'Column B in this case
endrow = Cells(Rows.Count, colnum).End(xlUp).Row

For n = 1 To endrow
    For i = 0 To UBound(list)
        If list(i) = Cells(n, colnum).Value Then
            inlist = True
            Exit For
        End If
    Next i

    If inlist = False Then
        ReDim Preserve list(0 To j)
        list(j) = Cells(n, colnum).Value
        j = j + 1
    End If

    inlist = False
Next n

For i = 0 To UBound(list)
    Debug.Print list(i)
Next i

End Sub

答案 1 :(得分:1)

使用脚本字典提供数组的可选解决方案,如果可能不需要的话。

Public Function Signals(ByRef this_worksheet_range As excel.Range) As Variant()

Dim myArray()       As Variant
Dim element         As Variant
Dim interim_dic     As Scripting.Dictionary

    myArray = this_worksheet_range.values2

    Set interim_dic = New Scripting.Dictionary

    For Each element In myArray
        If Not interim_dic.Exists(element) Then
            interim_dic.Add Key:=element, Item:=element
        End If
    Next

    Signals = interim_dic.Items

End Function