【问题标题】:How To create Macro that copy cells, paste them in the first available row and clear some content如何创建复制单元格的宏,将它们粘贴到第一个可用行并清除一些内容
【发布时间】:2019-12-17 10:52:25
【问题描述】:

我正在尝试创建一个复制一系列单元格的 VBA 宏,将它们粘贴到第一个可用行的同一张工作表中,然后清除复制的单元格的内容,留下公式。

到目前为止,我已经想出了复制/粘贴,但不是清晰的内容。

Range("A1:L5").Copy
Range("A1").End(xlDown).Offset(6).EntireRow.Insert
Range("B2:B4").ClearContents

【问题讨论】:

  • and then clear the content of the copied cells, **leaving the formulas**你能澄清这部分吗?
  • 留下公式,我的意思是我想清除我插入的单元格的内容,但留下计算公式。即:在一列中,用户手动插入一些值,而其他列则填充了基于插入值的计算公式。我想清除手动插入的值但留下公式,所以当用户插入新值时,其他单元格会自动填充

标签: excel vba


【解决方案1】:

将所有内容复制到目标,然后使用.SpecialCells(xlCellTypeConstants).Clear 清除目标中的所有常量值。

Option Explicit

Public Sub CopyFormattingsAndFormulasOnly()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.ActiveSheet

    Dim Source As Range
    Set Source = ws.Range("A1:L5")

    Dim Destination As Range
    Set Destination = ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(RowOffset:=1).Resize(Source.Rows.Count, Source.Columns.Count)

    Source.Copy

    Destination.PasteSpecial xlPasteAll
    On Error Resume Next
    Destination.SpecialCells(xlCellTypeConstants).ClearContents
    On Error Goto 0
End Sub

【讨论】:

  • 顺便说一句我用过On Error Resume Next: rng.SpecialCells(xlCellTypeConstants).ClearContents: On Error GoTo 0
  • @SiddharthRout 啊,对,如果我不测试代码,我总是会忘记这一点:/ 谢谢 :)
  • @SiddharthRout 我真的不应该在午饭前写答案^^
  • 我也犯了这些错误……很久以后今天犯了一个:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
相关资源
最近更新 更多