0
我有一個宏腳本來識別兩個打開的excel中的匹配列值(第一列中的列A和第二列中的列A)。我需要匹配的列值被複制到列A中的新Excel(第三Excel)。請指導我。在兩個打開的Excel中複製匹配列值的宏腳本
Sub Compare()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim Cell As Range
Dim sBook As String
If Workbooks.Count < 2 Then
MsgBox "Error: Only one Workbook is open" & vbCr & _
"Open a 2nd Workbook and run this macro again."
Exit Sub
End If
Set wb1 = ThisWorkbook
For Each wb2 In Workbooks
If wb2.Name <> wb1.Name Then Exit For
Next
On Error Resume Next
ReDo1:
Application.DisplayAlerts = False
sBook = Application.InputBox(Prompt:= _
"Compare this workbook (" & wb1.Name & _
") to...?", _
Title:="Compare to what workbook?", _
Default:=wb2.Name, _
Type:=2)
If sBook = "False" Then Exit Sub
If Workbooks(sBook) Is Nothing Then
MsgBox "Workbook: " & sBook & " is not open."
GoTo ReDo1
Else
Set wb2 = Workbooks(sBook)
End If
Application.ScreenUpdating = False
For Each ws1 In wb1.Sheets
If Not wb2.Sheets(ws1.Name) Is Nothing Then
Set ws2 = wb2.Sheets(ws1.Name)
For Each Cell In ws1.UsedRange
If Cell.Formula = ws2.Range(Cell.Address).Formula Then
Cell.Interior.ColorIndex = 35
ws2.Range(Cell.Address). _
Interior.ColorIndex = 35
End If
Next Cell
If ws1.UsedRange.Rows.Count = _
ws2.UsedRange.Rows.Count Or _
ws1.UsedRange.Columns.Count = _
ws2.UsedRange.Columns.Count Then
For Each Cell In ws2.UsedRange
If Cell.Formula = ws1.Range(Cell.Address).Formula Then
Cell.Interior.ColorIndex = 35
ws1.Range(Cell.Address). _
Interior.ColorIndex = 35
End If
Next Cell
End If
End If
Next ws1
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
最後兩行代碼(MaxRow),只是複製ws2的entier列。它不會將匹配的值複製到列A(Ws3)。與不匹配的值應該被刪除並且匹配的值應該按順序排列。 – Visitjaga
有沒有辦法用特定的顏色複製單元格?在我的情況下,這也將解決問題,因爲在新的excel ws3中,匹配值將以綠色(ColorIndex = 35)。因此具有綠色的單元格將按順序複製到新的excel(ws4)中。請幫忙。 – Visitjaga
我簡化了我的答案。我能夠使用比我原先認爲需要的更簡單的方法。 –