我正在尝试编写一个函数和一个调用这样一个函数的过程,以检查位于大型重复数据表中的项目的名称是否出现在不同的工作表上,这些工作表基本上类似于输入用户表或设置表。基本上,代码应该捕获Sheet2上的表中的拼写错误和不匹配的项目与Sheet1上的范围。理想情况下,我希望为代码添加一种能够停止在不匹配项目上的功能,并且可以突出显示它,以便用户可以纠正错误或进一步研究问题。目前我已经尝试编写代码的第一部分,但有些东西不起作用。无论我如何在表格中设置数据,它总是表示项目名称不存在:
Option Explicit
Public Function ItemNameExists(Target As String) As Boolean
Dim lookUp As Excel.Range
Dim itemCell As Excel.Range
ItemNameExists = False
Set lookUp = Worksheets("Sheet2").Range("Table1[Items]")
For Each itemCell In lookUp
If (itemCell.Value = Target) Then
ItemNameExists = True
Exit Function
End If
Next
End Function
Sub CheckErrors()
Dim ItemName As Excel.Range
Dim Cell As Range
Set ItemName = Worksheets("Sheet1").Range("B3:B12")
For Each Cell In ItemName
If (Len(Cell.Value) > 0) Then
If (Not ItemNameExists(Cell.Value)) Then
MsgBox ("Item name doesn't exist on Sheet1")
Exit Sub
End If
End If
Next
End Sub
答案 0 :(得分:0)
要搜索Range
,有一种特定的方法Range.Find
(官方文档here)。
如果未找到匹配项,则返回Nothing
。
至于你的情况,有很多点可能会错过目标,所以你可能需要调试:
lookUp
实际引用了预期的Range
。Target
包含预期文字。itemCell.Text
代替itemCell.Value
(如果您仍然不想使用Range.Find
)。