简体   繁体   中英

Copy and Paste cells x times and change Cell address

I need to copy cells A1:C10 , and paste them X times. The X is in the cell D1, also in the cell A1 i have a formula

=IF('C:\Users\..\..\\E kompletuar\[data.xlsx]data'!$H$2=0;"")

I need the Cell row $H$ 2 to change by the number of times the cells A1:C10 is pasted. eg. $H$ 3 (if i paste for first time), $H$ 4 (if i paste for second time),$H$ 5 (if i paste for third time) ...

I think this is what you're after

Sub foo()
Dim x as Long, numberOfTimes as Long 'number of times to "copy"
Dim rngToCopy as Range
Dim rngToPaste as Range
Dim A1_FORMULA as String

'## Define the range you want to copy:
Set rngToCopy = Range("A1:C10")

'## Get the number "X" from cell D1:
numberOfTimes = Range("D1").Value

For x = 1 to numberOfTimes

    '## Define your base formula:
    A1_FORMULA = "=IF('C:\Users\..\..\\E kompletuar\[data.xlsx]data'!$H$" & CStr(2 + x) & "=0;"""")"

    '# Determine where to paste:
    Set rngToPaste  = rngToCopy.Offset(x*(rngToCopy.Rows.Count + 2))

    '# Copy and Paste
    rngToCopy.Copy Destination:=rngToPaste

    '# Update the formula in the first copied cell/column A:
    rngToPaste.Cells(1,1).Formula = A1_FORMULA

Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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