【发布时间】:2019-07-09 01:59:17
【问题描述】:
我有一个宏循环遍历一张表的单元格,在另一张表中查找该值,然后在匹配时突出显示该行。我想添加一个消息框,如果找不到匹配的值会弹出。我知道这是一个简单的问题,但我无法确定将布尔值放在哪个循环中。
Sub MarkXfer_noX()
Dim rng As Range
Dim rng2 As Range
Set rng = Worksheets("Transferred Routings").UsedRange
Dim i As Integer
Dim j As Integer
Dim ProdCI As String
Dim found As Boolean
Dim intRowCount As Integer
intRowCount = Sheets("Transferred Routings").UsedRange.Rows.count
For i = 2 To intRowCount
If rng.Cells(i, 1) <> "" Then ProdCI = rng.Cells(i, 1) 'get the ProdCI number from column A if not blank
Worksheets("All_ProCI").Activate 'activate main page
Set rng2 = Worksheets("All_ProCI").UsedRange 'select a range on the main page
For j = 2 To rng2.Rows.count 'from row 2 to the end
If rng2.Cells(j, 2) = ProdCI Then 'if the ProdCI in column B matches the one we picked,
Call FillCell(j) 'call a sub in a different module and give it our current row
found = True
Else
found = False
End If
Next
Next
If found = False Then
MsgBox (ProdCI & " not found") 'Display a message if one of the items wasn't found on the main page. Currently has an error where the last one in the list always pops up.
Else
End If
End Sub
现在它总是显示一个带有范围内最后一个值的 msgbox。
【问题讨论】:
-
看这里:stackoverflow.com/questions/56854086/… 这是单列但概念是一样的。
-
(1) 找到后需要退出循环; (2) 使用
Find方法会比循环更有效。 -
除了@SJR 选项,(3) 你可以用
Index + Match公式来做到这一点(如果你真的想要的话,在你的VBA代码中)。 Excel 的 C++ 代码将胜过您编写的任何宏......只是提示 -
THIS 将帮助您开始