【发布时间】:2018-11-08 00:10:06
【问题描述】:
我有一个类似于VBA macro to compare two columns and color highlight cell differences 帖子中的问题。
我用它作为参考点,但现在我被困了好几个小时来解决我的问题。 代码包含在下面,我将首先解释我的案例以便更好地理解和更容易理解。
案例: 在进行任何操作之前,我有以下工作表。我正在比较列“A:B”和“D:E”等(从第 3 行到最后使用的行)。请参阅下面的屏幕截图以获得更好的可视化效果(这只是数据的一部分)。
现在我想查看执行的 2 个操作:
- 突出显示 A 列和 D 列中不属于 B 列和 E 列的单元格 - 我将这些单元格称为错误
- 将错误值(突出显示的单元格(来自 A 和 D))复制到 C 和 F 列(这是“审查列” - 相对于初始列,它始终是右侧的 2 列)
查看下面的屏幕截图以获得更好的可视化效果
代码:
Sub compare_cols()
Dim Report As Worksheet
Dim i As Integer, j As Integer
Dim lastRow As Integer
Set Report = Excel.Worksheets("Check_Sheet")
lastRow = 80
arrInputCheckSheet= Array("A", "D", "G", "J", "M", "P", "S", "V", "Y") 'I will use these columns to compare against the next array
arrMDCheckSheet = Array("B", "E", "H", "K", "N", "Q", "T", "W", "Z") 'I will use these columns as reference
Application.ScreenUpdating = False
For a = LBound(arrInputCheckSheet) To UBound(arrInputCheckSheet)
For i = 3 To lastRow
For j = 3 To lastRow
If Report.Cells(i, arrInputCheckSheet(a)).Value <> "" Then 'This will omit blank cells at the end (in the event that the column lengths are not equal.
If InStr(1, Report.Cells(j, arrMDCheckSheet(a)).Value, Report.Cells(i, arrInputCheckSheet(a)).Value, vbTextCompare) > 0 Then
Report.Cells(i, arrInputCheckSheet(a)).Interior.Color = RGB(156, 0, 6) 'Dark red background
Report.Cells(i, arrInputCheckSheet(a)).Font.Color = RGB(255, 199, 206) 'Light red font color
Exit For
Else
End If
End If
Next j
Next i
Next a
Application.ScreenUpdating = True
End Sub
问题:
- 我正在尝试用深红色背景突出显示错误单元格。但这段代码的作用恰恰相反(突出显示匹配的值)。
- 如何使错误值(突出显示的那个)出现在“检查列”中。
非常感谢您给我的任何建议和支持
非常感谢,祝你有美好的一天
【问题讨论】:
-
您是否尝试将
InStr(1, Report.Cells(j, arrMDCheckSheet(a)).Value, Report.Cells(i, arrInputCheckSheet(a)).Value, vbTextCompare) = 0中的> 0更改为= 0?这使它相反,应该是不匹配的值。 • 也不要使用Integer进行行计数。 Excel 的行数超过了 Integer 可以处理的数量。建议在 VBA 中使用 always to use Long instead of Integer,因为使用Integer根本没有任何好处。 -
@Pᴇʜ 感谢您的建议,问题是当我将 >0 更改为 =0 时,它只会突出显示所有单元格(字面意思)。
-
您是否在测试之前从所有单元格中删除了颜色?否则失败。
-
我建议使用WorksheetFunction.Match Method 而不是第二个
j循环。并使用Range.Offset Property 寻址偏移单元格以复制值。 -
是的,您可以使用
.Offset查看完整示例的答案