我试图比较两列中的所有单元格,每列都在不同的工作簿中。 单元格包含文本和数字,如果两个单元格(每个单元格在不同的工作簿中)不同,我希望其中一个单元格被突出显示/着色/填充。
任务:
1.1 - Cell1 = Hi
1.1 - Cell2 = Hi
因此,这里没有突出显示,两个值都相等
1.2 - Cell1 = Hello
1.2 - Cell2 = Hellod
此处需要突出显示,两个值都不相等
注意:Cell1和Cell2都在不同的工作簿中
以下是我目前的代码:
Sub DescriptionDiscrepency()
目标路径在我的代码中是多余的,但可能对你们有用
Target_Path = "C:\Users\Example.xlsm"
Set Target_Workbook = Workbooks("Example.xlsm")
Target_Workbook.Sheets("Sheet1").Unprotect Password:="****"
Set Source_Workbook = Workbooks("Example2.xlsm")
Source_Workbook.Sheets("Sheet1").Unprotect Password:="*****"
从目标文件中读取数据以查看源文件是否匹配
Target_Data = Target_Workbook.Sheets("Sheet1").Cells(2, 6).CurrentRegion.Rows.Count
Source_Data = Source_Workbook.Sheets("Sheet1`").Cells(5, 2).CurrentRegion.Rows.Count
如果我们的状态跟踪器中的CAT描述不相同
此部分无效
For i = 1 To lastRow
For j = 1 To lastRow
If Source_Data.Cells(j, 1).Value <> "" Then
If StrComp(Source_Data.Cells(j, 2).Value,
Target_Data.Cells(i, 6).Value, CompareMethod.Text) = 0 Then
Source_Data.Cells(j, 2).Interior.ColorIndex = RGB(255, 255, 255)
Source_Data.Cells(j, 2).Font.Color = RGB(0, 0, 0)
Else
Source_Data.Cells(j, 2).Interior.ColorIndex = RGB(0, 0, 0)
Source_Data.Cells(j, 2).Font.Color = RGB(255, 199, 206)
End If
End If
Next j
Next I
End Sub
答案 0 :(得分:0)
你混合了一些东西。即范围对象(Excel中的实际单元格)和行计数(简单数字)。
试试这样:
Set Target_Data = Target_Workbook.Sheets("Sheet1").Cells(2, 6).CurrentRegion
Set Source_Data = Source_Workbook.Sheets("Sheet1`").Cells(5, 2).CurrentRegion
For i = 1 To Target_Data.Rows.Count
For j = 1 To Source_Data.Rows.Count
If Source_Data.Cells(j, 1).Value <> "" Then
If StrComp(Source_Data.Cells(j, 2).Value, Target_Data.Cells(i, 6).Value, vbTextCompare) = 0 Then
Source_Data.Cells(j, 2).Interior.Color = RGB(255, 255, 255)
Source_Data.Cells(j, 2).Font.Color = RGB(0, 0, 0)
Else
Source_Data.Cells(j, 2).Interior.Color = RGB(0, 0, 0)
Source_Data.Cells(j, 2).Font.Color = RGB(255, 199, 206)
End If
End If
Next j
Next I
End Sub