在for-each循环中复制dynamic范围

为了完成这个任务,我花了几个星期的时间试图拼凑出一个完整的VBA,以完成这个任务,但现在我正在向你们所有人寻求答案。 我试图复制一个范围从ws2,列A:K的行开始与值匹配我在ws1中的值我到ws1中的价值我开始的行。 被复制的标准是1和0。 这基本上是一个美化的v-lookup粘贴dynamic范围。

我想出了循环机制,现在我只需要帮助编写复制选定单元格的代码。

以下是我到目前为止:

For Each i In ws1.Range("A4:A26") For Each c In ws2.Range("A8:A28") If i.Cells.Value <> c.Cells.Value Then 'select columns A:K in the row with the value c in ws2 'open ws1 'paste selection to[starting at] column D in ws1 Exit For End If Next c Next i 

如果你真的想要比赛,一旦find了比赛,然后退出For。
这是与没有激活或select

  For Each i In ws1.Range("A4:A26") For Each c In ws2.Range("A8:A28") If i.Value = c.Value Then 'select the row, columns A:K that starts with the value c in ws2 ws2.Range("A" & c.Row & ":K" & c.Row).Copy ws1.Range("A" & i.Row) Exit For End If Next c Next i 

不知道这是你的目标。 如果可以通过“select行,列A:K以ws1中的值c开头”来阐明您的意思,那可能会有所帮助。 我假设Exit For是如果值不匹配,你想在If语句中做所有事情后去下一个i

使用loggingmacrosfunction可能会有所帮助。

 For Each i In ws1.Range("A4:A26") For Each c In ws2.Range("A8:A28") If i.Cells.Value <> c.Cells.Value Then 'select the row, columns A:K that starts with the value c in ws2 ws2.Range(Cells(c.Cells.Value, "A"), Cells(c.Cells.Value, "K")).Copy 'open ws1 ws1.Activate 'paste selection, starting from column D in ws1, into ws1 ws1.Cells(i.Cells.Value, "D").Select ActiveSheet.Paste Exit For End If Next c Next i End Sub 

在2个工作表中比较2列中的值时,您具有Application.Match函数。 而不是有两个For循环,这是耗时的,你可以有一个For和使用Application.Match而不是另一个。

此外, 复制>>粘贴是一行命令,不需要SelectActivate任何东西。

 Option Explicit Sub CompareColumns() Dim ws1 As Worksheet Dim ws2 As Worksheet Dim MatchRng As Range, C As Range Dim MatchRow As Long Set ws1 = Worksheets("Sheet1") ' change "Sheet1" to your sheet's name Set ws2 = Worksheets("Sheet2") ' change "Sheet2" to your sheet's name ' set the matched range Set MatchRng = ws1.Range("A4:A26") With ws2 For Each C In .Range("A8:A28") ' use Match to see if there's a match If Not IsError(Application.Match(C.Value, MatchRng, 0)) Then MatchRow = Application.Match(C.Value, MatchRng, 0) + MatchRng.Row - 1 ' get the row of the match (add 4 since the range starts at row 4) ' copy >> paste is a 1-line command .Range(.Cells(C.Row, "A"), .Cells(C.Row, "K")).Copy Destination:=ws1.Range("D" & MatchRow) End If Next C End With End Sub