复制并粘贴单元格x次并更改单元格地址

时间:2015-10-12 16:01:02

标签: excel vba excel-vba copy-paste

我需要复制单元格 A1:C10 ,并将它们粘贴X次。 X在单元格D1中,也在单元格A1中具有公式

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

我需要Cell行$ H $ 2 来更改粘贴单元格 A1:C10 的次数。例如。 $ H $ 3 (如果我是第一次粘贴),$ H $ 4 (如果我第二次粘贴),$ H $ 5 (如果我第三次粘贴)......

1 个答案:

答案 0 :(得分:1)

我认为这就是你之后

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