如何为单独的excel工作表指定数据要复制到的行

o2g1uqev  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(122)

我想从一个Excel工作表的数据复制到另一个单独的工作表每隔一行。例如,要复制到的第一行将是单元格B2,直到E2。下一行需要复制到B8直到E8,然后从B14复制到E14。如何指定要复制到这些特定行的数据并跳过其他行?
在VB中,我能够获得要复制的数据,但无法指定确切的单元格。

Sub CopyData()
  ' Define the range of data that you want to copy
  Dim dataRange As Range
  Set dataRange = Range("A1:E1")

  ' Define the starting row and the interval at which you want to copy data
  Dim startRow As Integer
  Dim interval As Integer
  startRow = 2
  interval = 6

  ' Loop through each row
  For i = startRow To 1000
    ' Check if the current row is a row that you want to copy data into
    If i Mod interval = 0 Then
      ' Copy the data from the data range to the current row
      dataRange.Copy Cells(i, 2)
    End If
  Next i
End Sub
omhiaaxx

omhiaaxx1#

重复复制一个单行范围,带偏移量

Sub CopyRow()
    
    Const SRC_ROW As String = "A1:E1"
    Const DST_FIRST_CELL As String = "B2"
    Const DST_ROW_OFFSET As Long = 6
    Const DST_COPY_COUNT As Long = 3 ' 166
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim srg As Range: Set srg = ws.Range(SRC_ROW)
    Dim dCell As Range: Set dCell = ws.Range(DST_FIRST_CELL)
    
    Dim n As Long
    
    For n = 1 To DST_COPY_COUNT
        srg.Copy dCell
        Set dCell = dCell.Offset(DST_ROW_OFFSET)
    Next n
  
End Sub
gab6jxml

gab6jxml2#

当你执行For... Next循环时,你可以指定变量在两个循环之间的增量。默认值为1,但如果希望循环跳到下一行的第6行,只需指定For i = a to b Step 6即可

Sub CopyData()
  ' Define the range of data that you want to copy
  Dim dataRange As Range
  Set dataRange = Range("A1:E1")

  ' Define the starting row and the interval at which you want to copy data
  Dim startRow As Integer
  Dim interval As Integer
  startRow = 2
  interval = 6

  ' Loop through each row
  For i = startRow To 1000 Step interval
      ' Copy the data from the data range to the current row
      dataRange.Copy Cells(i, 2)
  Next i
End Sub

相关问题