用VBA编写一个过程,作用是分别找出sheet1和sheet2中,sheet1和sheet3中,列为“工卡号”下相同的单元格,并在sheet1中将其用不同的颜色标识出来,同时在列名为“工卡号”的旁边新插入一列,将与sheet1相同工卡号的sheet.name写进单元格
时间: 2024-01-23 12:03:54 浏览: 52
蓝牙室内定位人员定位标签5.0蓝牙工卡VDB1508规格书文档
好的,这里是根据您的要求编写的VBA代码:
```
Sub FindAndColorDuplicates()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim lastRow1 As Long, lastRow2 As Long, lastRow3 As Long
Dim i As Long, j As Long, k As Long
Dim cell1 As Range, cell2 As Range, cell3 As Range
Dim cardNum As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set ws3 = ThisWorkbook.Sheets("Sheet3")
lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
lastRow3 = ws3.Cells(ws3.Rows.Count, "A").End(xlUp).Row
'Loop through each row in Sheet1
For i = 2 To lastRow1
cardNum = ws1.Cells(i, "A").Value
If cardNum <> "" Then
'Loop through each row in Sheet2
For j = 2 To lastRow2
'Check if card number matches
If cardNum = ws2.Cells(j, "A").Value Then
'Color the cell in Sheet1
Set cell1 = ws1.Cells(i, "A")
cell1.Interior.Color = RGB(255, 255, 0) 'Change color here
'Write sheet name in new column
ws1.Cells(i, "B").Value = ws2.Name
'Exit inner loop since match is found
Exit For
End If
Next j
'Loop through each row in Sheet3
For k = 2 To lastRow3
'Check if card number matches
If cardNum = ws3.Cells(k, "A").Value Then
'Color the cell in Sheet1
Set cell1 = ws1.Cells(i, "A")
cell1.Interior.Color = RGB(255, 0, 0) 'Change color here
'Write sheet name in new column
ws1.Cells(i, "C").Value = ws3.Name
'Exit inner loop since match is found
Exit For
End If
Next k
End If
Next i
End Sub
```
这段代码会在Sheet1中查找与Sheet2和Sheet3中相同的工卡号,并将其用黄色和红色标记出来。在Sheet1中,新的两列将被添加在工卡号列的右侧,并将Sheet2和Sheet3的名称写入与匹配的行中。
请注意,此代码假定工卡号列为A列,新列将添加在B列和C列。如果您的列不同,请相应更改代码中的列号。
阅读全文