【问题标题】:How to properly code offset in a copy paste loop VBA如何在复制粘贴循环 VBA 中正确编码偏移量
【发布时间】:2017-10-02 12:25:23
【问题描述】:

我正在尝试复制然后粘贴到循环中的单元格中。使用单元格 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

【问题讨论】:

    标签: vba copy offset paste


    【解决方案1】:

    您只会得到单元格“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
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      相关资源
      最近更新 更多