我正在尝试比较两个列表(用户可以选择-它可以是数字值或文本(10个数字/字符长(不确定是否重要)),并在第一个列表中高亮显示单元格(红色)。我知道可以用条件格式来做,但是我想用VBA来做。
我在Debug.Print
的即时窗口中收到“错误2015”。
这是我到目前为止编写的代码:
Sub Colorcells()
Dim v1 As Range
Dim v2 As Range
Dim f As Variant
Set v1 = Application.InputBox("First list", "Obtain Range Object", Type:=8)
Set v2 = Application.InputBox("Second list", "Obtain Range Object", Type:=8)
lastv1 = v1.End(xlDown).Row
With Worksheets(1)
For i = 1 To lastv1
Debug.Print Application.Match(v1.Cells(i, 1), v2.Address)
f = Application.Match(v1.Cells(i, 1), v2.Address, 0)
If Not IsError(f) Then
v1.Cells(i, 1).Interior.ColorIndex = 3
End If
Next i
End With
End Sub
我试图将f数据类型更改为string / long,但是随后收到“类型不匹配”错误。 我还尝试将循环更改为(具有相同的错误2015结果):
For i = 1 To lastv1
If Not IsError(Application.Match(v1.Cells(i, 1), v2.Address, 0) then
v1.Cells(i, 1).Interior.ColorIndex = 3
End If
Next i
任何帮助将不胜感激。
答案 0 :(得分:4)
不使用匹配功能,而是使用“查找一个”,如下所示:
Sub Colorcells()
Dim v1 As Range
Dim v2 As Range
Dim found As Range
Set v1 = Application.InputBox("First list", "Obtain Range Object", Type:=8)
Set v2 = Application.InputBox("Second list", "Obtain Range Object", Type:=8)
For i = 1 To v1.Count
Set found = v2.Find(What:=v1.Cells(i, 1), LookAt:=xlWhole)
'find the value from v1 in v2
If found Is Nothing Then
'if not found then Color
v1.Cells(i, 1).Interior.ColorIndex = 3
End If
Next i
End Sub
答案 1 :(得分:2)