如何在循环中设置等于倒数第二个的范围?

时间:2015-10-11 09:44:00

标签: excel vba excel-vba while-loop named-ranges

我的数据列表长度接近92000行。它包含ICD10医疗诊断代码和代码类别标题。代码类别标题总是三个字符长(例如“A00”,“A01”,“B00”,“B01”)。但是,当紧跟着相同的代码并附加“0”(例如“A000”,“A010”,“B000”,“B010”)时,三个字符代码仅为类别标题。如果三个字符代码后面没有附加的版本,则三个字符代码本身就是一个代码。

最终目标是使用驻留在用户表单中的列表框提供数据验证列表。列表框必须只包含代码,不包括所有类别标题。

我的第一步是修改一些免费代码以循环92000行并构建一个范围,捕获所有类别标题以进行排除。我已经在检测到“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

3 个答案:

答案 0 :(得分:1)

如果您要搜索的值是单元格的全部内容,则可以修改初始查找调用以匹配整个单元格。

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

变为

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

答案 1 :(得分:1)

要确保针对单元格的整个值执行匹配,需要将LookAt的{​​{1}}参数设置为Range.Find

此外,由于xlWhole方法的某些设置在每次使用时都会保存,因此最好始终明确设置这些参数(请参阅Range.Find Method

要更正此行:

Range.Find

用这些:

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

答案 2 :(得分:0)

我不确定我是否遗漏了一些明显的东西,但您是否只是获取了长度仅为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