【问题标题】:Filter without duplicates and add to listbox column 1过滤无重复项并添加到列表框第 1 列
【发布时间】:2019-11-05 19:13:31
【问题描述】:

此代码用于查找第一个值,我需要它来捕获其中包含“120”的第一个单元格,这意味着 120、7120、31200 都包含重复项。另外,ID CODE 在 C 列,如何将 D 列的数据添加到列表框的第二列?

Dim AGCN As Long
Dim AGCL As String
Dim AGNN As Long
Dim AGNL As String
Dim i As Long
Dim rng As Range
Dim rownumber As Long
Dim AGC As Range
Dim AGN As Range
Dim firstaddress As Long
Dim nextaddress As Long

'Identify column letter
AGCN = Rows("1:1").Find(what:="ID CODE", lookat:=xlWhole).Column
AGCL = Split(Cells(1, AGCN).Address, "$")(1)

AGNN = Rows("1:1").Find(what:="NAME", lookat:=xlWhole).Column
AGNL = Split(Cells(1, AGNN).Address, "$")(1)


With Sheet1.Range(AGCL & ":" & AGCL)
    Set c = .Find("*" & tbAC & "*", LookIn:=xlValues)
    If Not c Is Nothing Then
        firstaddress = c.Value
        Debug.Print firstaddress
            With Me.ListBox2
           .ColumnCount = 3
           .ColumnWidths = "50;150;70"
           .AddItem
           .List(i, 0) = Str(firstaddress)
           i = o + 1
           End With ' code works up till this part

    Do ' from here, 
        Set c = .FindNext(c)
        If c Is Nothing Then
            GoTo donefinding
        ElseIf firstaddress <> c.Value Then
            nextaddress = c.Value
            Debug.Print nextaddress
            With Me.ListBox2
                .ColumnCount = 3
                .ColumnWidths = "50;150;70"
                .AddItem
                .List(i, 0) = Str(nextaddress)
                Debug.Print nextaddress
                i = o + 1
            End With
        End If
    Loop While c.Address <> firstaddress ' till here, it loops through all the other possible values but does not input onto listbox and it crashes my excel

End If
donefinding: Exit Sub
End With

目前没有错误信息,excel只是循环和崩溃。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果o + 1 的值大于列表框项的计数,.List(i, 0) = ... 将崩溃,但这会在第一个循环中发生。

    否则,您在每个循环中使用i = o + 1,这样i 的值就不会改变,因此您会继续覆盖列表框中的相同项目。所以列表框项目的数量在每个循环中都会增加,但您只能在第一个位置看到最新的值(我假设 o 的值是 0)。

    其他建议: 您可以像这样简化.Find 的启动:

    AGCN = Rows("1:1").Find(what:="ID CODE", lookat:=xlWhole).Column
    With Sheet1.Columns(AGCN)
         Set c = .Find(tbAC, LookIn:=xlValues, LookAt:=xlPart)   ' you can omit "*" by using xlPart
         ...
    

    您可以将列表框中的第 2、第 3 等列视为基于 0 的“数组”:

    .List(i, 1) = "Something"    ' will put "Something" to column 2
    .List(i, 2) = "Anything"    ' will put "Anything" to column 3
    

    您无需在每个循环中重复设置.ColumnCount.ColumnWidths

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2018-08-21
      • 2012-12-12
      • 2014-03-05
      • 1970-01-01
      相关资源
      最近更新 更多