首页 > 解决方案 > 循环遍历单元格,直到找到相同的字符串

问题描述

我浏览了以前有关此问题的帖子,但似乎找不到解决方案。我正在尝试遍历一些代码行,仅在找到与我输入的字符串匹配的字符串时才停止。

我遇到的问题是我的代码只比较第一个单元格的值。如果不匹配,则继续退出循环。换句话说,我的代码没有循环。

Public Function CO_Score(co_name As String) As Integer
Dim row_counter As Long
    row_counter = 3 'Where the CO Scores start
Dim ref_name As String
    ref_name = Worksheets("CO_Scorecard").Cells(row_counter, 2).Value
Dim co_total As Integer
    co_total = Worksheets("CO_Scorecard").Range("R3").Value + 10 'Add some extra buffer
Dim co_found As Integer
    co_found = 1

Do While StrComp(co_name, ref_name, vbTextCompare) = 0
    row_counter = row_counter + 1
    co_found = co_found + 1 '
    ref_name = Worksheets("CO_Scorecard").Cells(row_counter, "M").Value

    If row_counter > co_total Then
        co_found = 0
        Exit Do
    End If
Loop

If co_found = 1 Then
    CO_Score = Worksheets("CO_Scorecard").Cells(row_counter, "M").Value
Else
    CO_Score = 0
End If

End Function

在此先感谢您的帮助!

标签: vbaexcel

解决方案


请尝试以下代码。我相信您想比较string列中的值,如果string匹配,则需要捕获该单元格。

Sub SO3()

Dim InputValue As String
Dim GetCellValue, NumberOfValues As String
Dim i As Integer

InputValue = Worksheets("CO_Scorecard").Range("B1").Value

'number of values in column
NumberOfValues = Worksheets("CO_Scorecard").Range("A1").End(xlDown).Row

For i = 1 To NumberOfValues
GetCellValue = Worksheets("CO_Scorecard").Range("A" & i).Value
If GetCellValue = InputValue Then
MsgBox "Match found in A" & i & " cell"
End If
Next

End Sub

推荐阅读