如何在复制粘贴循环VBA中正确编码偏移量

时间:2017-10-02 12:25:24

标签: vba copy offset paste

我试图复制然后粘贴到循环中的单元格中。使用单元格BP3作为原始参考,我试图编写它,使得在每次迭代之后它粘贴到BP3的下一个单元格,即BP4。但我目前只是在BP4单元格中重复。

' Copy and Paste of CAPEX 4 forecast dates from VR all DVs
Dim Updated_Spreadsheet As Workbook
Dim wb As Workbook: Set wb = Workbooks("study tracker.xlsm")

Set Updated_Spreadsheet = Workbooks("VR.xlsm")
Set sht = Updated_Spreadsheet.Sheets("Variance Report")
Set sht2 = wb.Sheets("Environmental Studies")

'Loop
Dim cell As Range, lRow As Long, NextRow As Long, lngDataRows As Long
For Each cell In sht2.Range("A3", sht2.Range("A" & Rows.Count).End(xlDown))
  'specifying cell i want to use as a criteria for the filter
  'cell = sht2.Range("A3").Value
  sht.Activate

  'specifying filter range
  sht.Range("$A$7:$GV$4694").AutoFilter Field:=1, Criteria1:=cell

  'specifying the exact cell from the filter which I would like to copy
  sht.UsedRange.SpecialCells _
    (xlCellTypeVisible).Areas(2).Columns(171).Cells(1, 1).Copy
  wb.Activate

  'pasting into new location
  lngDataRows = cell.CurrentRegion.Rows.Count - 1
  Range("BP3").Offset(lngDataRows + 1, 0).Select
  Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Next cell

1 个答案:

答案 0 :(得分:0)

你只获得单元格“BP4”,因为每次循环运行时,你都会一遍又一遍地选择相同的单元格。 启动一个变量(在开始循环之前),每次循环迭代都会增加一个变量。

OffsetBy = 1
'Your "For Each" loop starts here
'(...)
'Use this variable in here:
Range("BP3").Offset(lngDataRows + OffsetBy, 0).Select
OffsetBy = OffsetBy + 1
Next cell

希望这有帮助!