简体   繁体   English

通过 Excel VBA 复制粘贴单元格

[英]Copy Paste Cells through Excel VBA

I have wrote a code which copies the Sheet1 Cells A2 and B2 then paste that cells into Sheet2 Cells G5 and G6.我编写了一个代码,它复制 Sheet1 单元格 A2 和 B2,然后将这些单元格粘贴到 Sheet2 单元格 G5 和 G6 中。

I have been trying to create a loop that after first scenario when i run the code again it should copy the Cells A3 and B3 then paste into Cells G5 and G6 (these cell will always be same) .我一直在尝试创建一个循环,在第一个场景之后,当我再次运行代码时,它应该复制单元格A3 and B3然后粘贴到Cells G5 and G6 (these cell will always be same)

I want to step forward by one row every time i run the macro.每次运行宏时,我都想前进一排。

I have tried with OFFSET function but it works just once.我尝试过使用 OFFSET function 但它只工作一次。

Sub copy()
Dim lRow, i As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set sht1 = Sheet1
Set sht2 = Sheet2

sht1.Cells(2, 1).Offset(1, i).Copy Destination:=sht2.Cells(5, 7)
sht1.Cells(2, 2).Offset(1, i).Copy Destination:=sht2.Cells(6, 7)
End Sub

every time you run, locate the previous value in the input table and copy the next value每次运行时,在输入表中定位上一个值并复制下一个值

option explicit

Sub copy()

Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set sht1 = Sheet1
Set sht2 = Sheet2



dim r as range
set r = range(sht1.Cells(2, 1), sht1.Cells(2, 1).end(xlDown))

dim offset_row as variant

if isempty(sht2.Cells(5, 7).value) then
  offset_row=0
else
  offset_row=application.worksheetfunction.match(sht2.Cells(5, 7).value, r, 0)
endif

if not iserror(offset_row) then
  if offset_row <> r.rows.count then
    sht1.Cells(2, 1).offset(offset_row, 0).Copy Destination:=sht2.Cells(5, 7)
    sht1.Cells(2, 1).offset(offset_row, 1).Copy Destination:=sht2.Cells(6, 7)
  endif
endif



End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM