此代码可以找到第一个值,我需要它来捕获第一个包含“ 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仅会循环并崩溃。
答案 0 :(得分:0)
如果.List(i, 0) = ...
的值大于列表框项目的数量,则o + 1
将崩溃,但这将在第一个循环中立即发生。
否则,在每个循环中都使用i = o + 1
,因此i
的值不会改变,因此您将覆盖列表框中的同一项目。因此,列表框项目的数量在每个循环中都会增加,但是您只能在第1个位置看到最新的值(我假设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
...
您可以通过将其视为基于0的“数组”来处理列表框中的第二,第三列。
.List(i, 1) = "Something" ' will put "Something" to column 2
.List(i, 2) = "Anything" ' will put "Anything" to column 3
您不需要在每个循环中重复设置.ColumnCount
和.ColumnWidths
。