如何设置一个范围等于倒数第二个结果?

我有一个92000行的数据列表。 它包含ICD10医疗诊断代码和代码分类标题。 代码分类标题总是三个字符(例如“A00”,“A01”,“B00”,“B01”)。 但是,三个字符代码只有紧跟在后面跟着相同的代码(例如“A000”,“A010”,“B000”,“B010”)的类别标题。 如果三个字符代码没有跟随附加版本,那么这三个字符代码本身就是代码。

最终目标是使用驻留在用户窗体中的列表框提供数据validation列表。 列表框只能包含代码,不包括所有的类别标题。

我的第一步是修改一些免费的代码来循环92000行,并build立一个范围,捕捉所有的类别标题排除。 在检测到“A00”+“0”实例时,我已经尽可能地停止循环。 我怎么得到的结果只突出“A00”的价值,没有别的?

Sub HighlightFindValues() 'PURPOSE: Highlight all cells containing a specified values 'SOURCE: www.TheSpreadsheetGuru.com Dim fnd As String, FirstFound As String Dim FoundCell As Range, rng As Range Dim myRange As Range, LastCell As Range 'What value do you want to find (must be in string form)? fnd = "A00" 'Limit test range to 16 lines Set myRange = ThisWorkbook.Worksheets("Validation table").Range("M4:M20") Set LastCell = myRange.Cells(myRange.Cells.Count) Set FoundCell = myRange.Find(what:=fnd, after:=LastCell) 'Test to see if anything was found If Not FoundCell Is Nothing Then FirstFound = FoundCell.Address Else GoTo NothingFound End If Set rng = FoundCell 'Loop until cycled through all unique finds 'Do Until FoundCell Is Nothing '----->Change to "Do until FoundCell = result string + 0" Do While FoundCell <> fnd & "0" 'Find next cell with fnd value Set FoundCell = myRange.FindNext(after:=FoundCell) 'Add found cell to rng range variable '----->Change rng value to just the 1st result found 'Set rng = Union(rng, FoundCell) 'Test to see if cycled through to first found cell If FoundCell.Address = FirstFound Then Exit Do Loop 'Highlight Found cells yellow rng.Interior.Color = RGB(255, 255, 0) Exit Sub 'Error Handler NothingFound: MsgBox "No values were found in this worksheet" End Sub 

如果您正在search的值是单元格的全部内容,那么您可以修改您的初始查找调用以匹配整个单元格。

 Set FoundCell = myRange.Find(What:=fnd, After:=LastCell) 

 Set FoundCell = myRange.Find(What:=fnd, After:=LastCell, LookAt:xlWhole) 

为了确保匹配是针对单元格的整个值执行的,需要将Range.FindLookAt参数设置为xlWhole

此外,由于每次使用Range.Find方法时都会保存一些设置,所以始终明确地设置这些参数是一个很好的做法(请参阅Range.Find方法 )

要更正这一行:

 Set FoundCell = myRange.Find(What:=fnd, After:=LastCell) 

用这些:

 Set FoundCell = myRange.Find(What:=fnd, After:=LastCell, _ LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 

不知道我是否错过了一些显而易见的东西,但是不是只是获取长度只有3个字符的文本的单元格吗?

 Dim myRange As Range Dim cell As Range Set myRange = ThisWorkbook.Worksheets("Sheet1").Range("M4:M20") For Each cell In myRange.Cells If Len(cell.Text) = 3 Then UserForm1.ListBox1.AddItem cell.Text End If Next 

更新:

那么你是说如果第一个单词只有3个字符长的话就拿这个代码呢? 如果第一个单词总是被一个空格隔开,那么可能是下面的那个对你有用:

 Dim myRange As Range Dim cell As Range Dim ICDCode as String Set myRange = ThisWorkbook.Worksheets("Sheet1").Range("M4:M20") For Each cell In myRange.Cells If Len(cell.Text) > 0 Then ICDCode = Split(cell.Text, " ")(0) If Len(ICDCode) = 3 Then ICDCode = ICDCode & "0" UserForm1.ListBox1.AddItem ICDCode End If End If Next