我正在创建一个代码,用于比较两个不同的工作簿(一个" master"和一个" slave")并且我想要复制在wb1中创建的所有行(&#34) ;主人)进入wb2("奴隶")
的同一地点为此,我使用以下代码作为一部分:
Sub CopySchedule()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim LastCell As Range
Dim ws As Integer
Dim MasterCell As Range
Dim GetRange As Range
Dim RowCount As Integer
Dim SlaveCell As Integer
Dim CheckN As Integer
Set wb1 = Application.Workbooks("Master Sheet.xlsx")
Set wb2 = ThisWorkbook
'Application.ScreenUpdating = False
For ws = 1 To wb1.Worksheets.Count
Set ws1 = wb1.Worksheets(ws)
Set ws2 = wb2.Worksheets(ws)
With ws1
RowCount = ws2.Cells(.Rows.Count, "A").End(xlUp).Row
Set LastCell = .Cells(1, Columns.Count)
For Each MasterCell In .Range("A4", LastCell)
CheckN = 0
For SlaveCell = 1 To RowCount
If MasterCell.Value = ws2.Cells(SlaveCell, "A").Value Then
CheckN = 1
GoTo Line1
End If
Next SlaveCell
Line1:
Set GetRange = Range(MasterCell.Address(0, 0))
MsgBox Range("GetRange").Address(0, 0)
If CheckN = 1 Then
Else
ws2.Range("GetRange").EntireRow.Insert
ws1.Range("GetRange").EntireRow.Copy Destination:=ws2.Range("GetRange")
End If
Next MasterCell
End With
Next ws
我遇到的问题是,一旦我找到了一个不在wb2中的MasterCell值,我需要在wb2中插入一行与Mastercell在wb1中的相同范围。然后我将行从wb1复制到wb2。
我遇到的问题是如何处理" MasterCell",这是一个看起来像
的范围值wb1.Range("whatever cell it's on in the for loop")
并在wb2中引用相同的单元格。
有没有人有解决方案?
谢谢!
答案 0 :(得分:0)
您的变量Mastercell
是一个范围,包含范围的所有属性。因此,您可以使用
myRow = Mastercell.row
然后使用myRow
来解决其他工作表中的相应行
ws2.Range("A" & myRow).EntireRow.Insert
ws1.Range("A" & myRow).EntireRow.Copy Destination:=ws2.Range("A" & myRow)