从一个工作表复制不同长度的粘贴范围内使用Excel VBA另一个工作表

问题描述 投票:0回答:1

我有一个设置为输出如下数据:

  • 数据的4列
  • 然后该数据由4分空白列分离,然后有数据等的另一个4列
  • 行的长度不同
  • 该数据是从彭博拉到等行可能会改变每一个数据刷新时间。
  • 数据在3行和列2开始。

enter image description here

我想创建一个循环,

  • 选择在另一个工作表中的整个4列,复制和粘贴它们
  • 然后在4个空白栏,复制数据并将其粘贴在其他工作表右下方先前粘贴的数据移动
  • 直至达到与数据的最后一列。
  • 我想在每间创建一个空白行,我也想保持彼此相邻的4列,当我粘贴他们到新的工作表

enter image description here

这里是我遇到的麻烦的代码....

Sub CopyPasteDex()

  Dim wksDest             As Worksheet
  Dim wksSource           As Worksheet
  Dim Rngsource           As Range
  Dim NextRow             As Long
  Dim LastRow             As Long
  Dim LastCol             As Long
  Dim c                   As Long

Application.ScreenUpdating = False

Set wksSource = Worksheets("Sheet1")
Set wksDest = Worksheets("Sheet2")

With wksDest
    NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With

With wksSource
    LastCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
    For c = 2 To LastCol Step 7
        LastRow = .Cells(.Rows.Count, c).End(xlUp).Row
        Set Rngsource = .Range(.Cells(3, c), .Cells(LastRow, c + 3))
        Rngsource.Copy
        wksDest.Range("A:A").PasteSpecial.xlPasteValues
        NextRow = NextRow + Rngsource.Rows.Count
    Next c
End With

Application.ScreenUpdating = True

End Sub
excel vba loops range copy-paste
1个回答
0
投票

enter image description here

这似乎为我工作。

Sub CopyPasteDex()

  Dim wksDest             As Worksheet
  Dim wksSource           As Worksheet
  Dim Rngsource           As Range
  Dim NextRow             As Long
  Dim LastRow             As Long
  Dim LastCol             As Long
  Dim c                   As Long

Application.ScreenUpdating = False

Set wksSource = Worksheets("Sheet1")
Set wksDest = Worksheets("Sheet2")

With wksDest
    NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With

With wksSource
    LastCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
    For c = 2 To LastCol Step 8    ' make sure that the step is changed to 8 here.
        LastRow = .Cells(.Rows.Count, c).End(xlUp).Row
        Set Rngsource = .Range(.Cells(3, c), .Cells(LastRow, c + 3))
        Rngsource.copy
        wksDest.Cells(NextRow, 1).PasteSpecial xlPasteValues    ' Note that I've changed .range to .cells and changed the destination row to NextRow
        NextRow = NextRow + Rngsource.Rows.Count
    Next c
End With

Application.ScreenUpdating = True

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.