vba - 循环遍历单元格,直到找到相同的字符串
问题描述
我浏览了以前有关此问题的帖子,但似乎找不到解决方案。我正在尝试遍历一些代码行,仅在找到与我输入的字符串匹配的字符串时才停止。
我遇到的问题是我的代码只比较第一个单元格的值。如果不匹配,则继续退出循环。换句话说,我的代码没有循环。
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
在此先感谢您的帮助!
解决方案
请尝试以下代码。我相信您想比较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
推荐阅读
- css - 使用 ::after 选择器的按钮悬停效果不可见
- c# - 是否可以使用 LINQ 指定内联数组?
- javascript - Webpack 同时使用 css 模块并导入整个 css 文件
- wordpress - 默认媒体上传器未显示在 wordpress 网站中
- javascript - 使用ajax和laravel访问路由时如何修复404未找到
- javascript - 使用 Google App 脚本将数据从一张表复制到另一张表时执行缓慢
- java - 如何使用 Java Stream 运算符获取子值的子值并作为地图收集
- android - Firebase ML Kit Android - API 密钥无效
- apache-kafka - Zookeeper 在 Kafka 最新版本中是否已弃用?
- flutter - 根据风味支持不同的资产集