如果我能得到一些关于尝试创建 vba 宏的问题的帮助,我将不胜感激。我有两个工作簿,我想比较工作簿 1 中的“N”列和工作簿 2 中的“F”列。然后,如果匹配,则移动到下一个单元格,如果未找到匹配项,我想复制工作簿 2 中“F”列后的下一个单元格。每天早上我拿到工作簿 2 时,它的名字不会相同,但工作簿名称总是以“Copy of”开头,所以我创建了下面的代码来使用部分名称选择它。
For Each ws In ActiveWorkbook.Worksheets
If ws.Name Like "Copy of*" Then
ws.Select
Exit For
End If
Next ws
即使我能得到正确的方向,那就太棒了。
答案1
这个解释不太清楚
...如果有匹配项,则移动到下一个单元格,如果没有找到匹配项,我想复制工作簿 2 中“F”列后的下一个单元格...
但尝试这样做,并进行相应的修改
Option Explicit
Public Sub CompareWorkBooks()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Set ws2 = GetWSCopy("Copy of*")
If Not ws2 Is Nothing Then
Dim r As Long, cel As Range, found As Variant, ws2lr As Long
optimizeXL True
For r = ws1.UsedRange.Rows.Count To 1 Step -1
Set cel = ws1.Cells(r, ws1.Columns("N").Column)
If Len(cel.Value2) > 0 Then
found = Application.Match(cel.Value2, ws2.UsedRange.Columns("F"), 0)
If Not IsError(found) Then 'a match was found so move next cell down
cel.Offset(1).EntireRow.Insert xlDown
Else 'match not found so copy row from ws1 to first empty row of ws2
ws2lr = ws2.UsedRange.Rows.Count + 1
ws1.UsedRange.Rows(cel.Row).EntireRow.Copy ws2.Cells(ws2lr, 1)
End If
End If
Next
optimizeXL False
End If
End Sub
Private Function GetWSCopy(ByVal wsName As String) As Worksheet
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like wsName Then
Set GetWSCopy = ws
Exit Function
End If
Next
End Function
Public Sub optimizeXL(Optional ByVal settingsOff As Boolean = True)
With Application
.ScreenUpdating = Not settingsOff
.Calculation = IIf(settingsOff, xlCalculationManual, xlCalculationAutomatic)
.EnableEvents = Not settingsOff
End With
End Sub
另外,您指的是 2 个工作簿(文件),
但您的代码指的是工作表(同一工作簿内的选项卡)