首页 文章

复制并粘贴到下一个可用列

提问于
浏览
0

我正在尝试跟踪我在电子表格中的每周数量 . 到目前为止,我已经制作了一个宏来复制和粘贴我需要的信息 . 但它只会将它粘贴到录制宏时我选择的位置 . 我希望将信息粘贴到下一个可用列中 .

我还想安排宏在星期五早上每周运行一次 .

宏我现在正在使用 .

Sub CopyPaste()
'
' CopyPaste Macro
'

'
   Range("G4:G33").Select
   Selection.Copy
   Range("B35").Select
   Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End Sub

我已经尝试将&lastrow放入范围,但它会出现编译错误 . 任何帮助将不胜感激 .

2 回答

  • 0

    乍一看可能稍微复杂一点,但在某种程度上,一种更好的解决 Value 运动的方法是避免使用带有如下代码的剪贴板:

    Sub CopyPaste()
    '
    ' CopyPaste Macro
    '
    '
    Dim targetRng As Excel.Range
    Dim destRng As Excel.Range
    Set targetRng = Range("G4:G33")
    
    Dim lc As Long
    With Excel.ThisWorkbook.Sheets("Sheet1")
        lc = .Cells(35, .Columns.Count).End(Excel.xlToLeft).Column
        Set destRng = .Range(.Cells(35, lc), .Cells(35, lc)).Offset(0, 1).Resize(targetRng.Rows.Count, targetRng.Columns.Count)
        destRng.Value = targetRng.Value
    End With
    
    End Sub
    

    以上内容可以简化为以下内容,因此您无需担心使用最后一行变量:

    Sub CopyPaste()
    '
    ' CopyPaste Macro
    '
    '
    Dim targetRng As Excel.Range
    Dim destRng As Excel.Range
    Set targetRng = Range("G4:G33")
    
    With Excel.ThisWorkbook.Sheets("Sheet1")
        Set destRng = .Cells(35, .Columns.Count).End(Excel.xlToLeft).Offset(0, 1).Resize(targetRng.Rows.Count, targetRng.Columns.Count)
        destRng.Value = targetRng.Value
    End With
    
    End Sub
    
  • 1

    您可以像这样计算出最后一列的列号:

    Sub CopyPaste()
    '
    ' CopyPaste Macro
    '
    Dim lastCol As Long
    ' this finds the number of the last column
    lastCol = Cells(35, Columns.Count).End(xlToLeft).Column
    
       Range("G4:G33").Copy
    
    '   Range("B35").Select
    ' no need to select. paste into the cell in row 35, one to the right of the last column
       Cells(35, lastCol + 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    End Sub
    

    你也可以在lastCol定义中添加1,比如

    lastCol = Cells(35, Columns.Count).End(xlToLeft).Column + 1
       Range("G4:G33").Copy
       Cells(35, lastCol).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
          :=False, Transpose:=False
    

    对于调度宏看看这两个问题herehere

相关问题