簡體   English   中英

通過 Excel VBA 復制粘貼單元格

[英]Copy Paste Cells through Excel VBA

我編寫了一個代碼,它復制 Sheet1 單元格 A2 和 B2,然后將這些單元格粘貼到 Sheet2 單元格 G5 和 G6 中。

我一直在嘗試創建一個循環,在第一個場景之后,當我再次運行代碼時,它應該復制單元格A3 and B3然后粘貼到Cells G5 and G6 (these cell will always be same)

每次運行宏時,我都想前進一排。

我嘗試過使用 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

每次運行時,在輸入表中定位上一個值並復制下一個值

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