【问题标题】:copy and paste to the next cell using a loop with the datas in different columns使用不同列中的数据循环复制并粘贴到下一个单元格
【发布时间】:2019-04-24 23:58:04
【问题描述】:

您好,我是 VBA 的新手,我想循环这段代码。截至目前,此代码正在将范围(“B30:B”)中的数据从“Ba Pricing”复制到目标工作表,并将相同的数据复制到最后一个单元格。我想做的是循环这段代码,它将复制列(E、H、K 和 N)中的数据并将其粘贴到“Loader”工作表的最后一个单元格。如果每列都没有数据,则不复制。

谢谢

Sub Copy_Paste_Below_Last_Cell()
'Find the last used row in both sheets and copy and paste data below existing data.

Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long

  'Set variables for copy and destination sheets
  Set wsCopy = ThisWorkbook.Worksheets("Ba pricing")
  Set wsDest = ThisWorkbook.Worksheets("Loader")

  '1. Find last used row in the copy range based on data in column A
  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "B").End(xlUp).Row

  '2. Find first blank row in the destination range based on data in column A
  'Offset property moves down 1 row
  lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "C").End(xlUp).Offset(1).Row

  '3. Copy & Paste Data
  wsCopy.Range("B30:B" & lCopyLastRow).Copy
    wsDest.Range("C" & lDestLastRow).PasteSpecial xlPasteValues


End Sub

它应该看起来像这样......

PriceDate
4/23/2019
4/24/2019
4/25/2019
4/26/2019
4/27/2019
4/28/2019
4/29/2019
4/30/2019
5/1/2019
5/2/2019
5/3/2019
5/4/2019
5/5/2019
5/6/2019
5/7/2019
5/8/2019
5/9/2019
5/10/2019
5/11/2019
5/12/2019
5/13/2019
5/14/2019
5/15/2019
5/16/2019
4/23/2019
4/24/2019
4/25/2019
4/26/2019
4/27/2019
4/28/2019
4/29/2019
4/30/2019
5/1/2019
5/2/2019
5/3/2019
5/4/2019
5/5/2019
5/6/2019
4/23/2019

【问题讨论】:

    标签: excel vba loops


    【解决方案1】:

    这是一个如何遍历列的示例

    Dim CopyColumns() As Variant
    CopyColumns = Array("B", "E", "H", "K", "N")
    
    Dim Col As Variant
    For Each Col In CopyColumns
    
        lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "C").End(xlUp).Offset(1).Row
        lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, Col).End(xlUp).Row
    
        wsCopy.Range(Col & "30:" & Col & lCopyLastRow).Copy
        wsDest.Range("C" & lDestLastRow).PasteSpecial xlPasteValues
    
    Next Col
    

    【讨论】:

    • 对不起,我应该更清楚。我想要做的是从数组 B30:B、E30:E、H30:H、K30:K、N30:N 中的“wsCopy”中复制每一列的日期,并将其全部粘贴到 C 列“wsDest”中.那可能吗? @Pᴇʜ
    • @thanh1211 查看我的编辑。请注意,Col 包含列名称,例如 "B" ...
    • 谢谢!这行得通!我还有一个问题....有没有办法做同样的事情,它填充 C 列,但这次用不同的数据填充 H 列?
    • H 列中的范围(与 C 列中填充的行相同)将是 wsDest.Range("H" & lDestLastRow, "H" & lDestLastRow + lCopyLastRow - 29) 只是在那里填充您的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多