我已经阅读了有关此问题的先前文章,但似乎找不到解决方案。我试图遍历一些代码行,仅在找到与我输入的字符串匹配的字符串时停止。
我遇到的问题是我的代码仅比较第一个单元格的值。如果不匹配,它将继续退出循环。换句话说,我的代码没有循环。
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
预先感谢您的帮助!
答案 0 :(得分:0)
请尝试以下代码。我相信您想比较一列中的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
答案 1 :(得分:0)
co_found
仅作为行计数器递增,因此您无法检查是否已找到样本。另外,StrComp
仅在字符串匹配时才返回0
。
纠正这两个缺陷的(imho)更易读的版本可能是:
Public Function CO_Score(co_name As String) As Integer
row_counter = 3
maxrow = Worksheets("CO_Scorecard").Range("R3").Value
Do While StrComp(co_name, Worksheets("CO_Scorecard").Cells(row_counter, "M").Value, vbTextCompare) <> 0 _
And row_counter < maxrow
row_counter = row_counter + 1
Loop
If row_counter < maxrow Then 'found?
CO_Score = Worksheets("CO_Scorecard").Cells(row_counter, "N").Value ' different column?
Else
CO_Score = 0
End If
End Function
编辑:
也许您想看看LOOKUP
和/或VLOOKUP
函数。也许您实际上根本不需要VBA。