在 VBA 中的 ClearContents 之后粘贴

Pasting after ClearContents in VBA

我正在尝试将数据从 table 复制到另一个 sheet。

Sub ListOfSquads()
  
    Sheets("Apontamentos").Select
    Range("Apontamentos[[#Headers],[Área]]").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    
    ThisWorkbook.Sheets("Squads").Select
        
    ThisWorkbook.Sheets("Squads").Columns("A:A").ClearContents
    
    ThisWorkbook.Sheets("Squads").Range("A1").Select
    
    ThisWorkbook.Sheets("Squads").Paste
    
    Application.CutCopyMode = False

End Sub

ClearContents 命令正在制作一个

Run-Time error '1004'> Application-defined or object-defined error.

复制ExcelTable列(ListColumn.Range)

  • 在您的代码中,当您执行 ClearContents 时,您实际上从剪贴板中删除了复制的范围。正如蒂姆威廉姆斯在评论中建议的那样,您必须将 ClearContents 行移动到 Selection.Copy 行之前并适当地重新排列 Select 行。
  • 使用 SelectMacro Recorder 'thing',最好在您的代码中避免使用,如所述
    在这个 legendary post.
  • 此代码使用 Range.Copy method.
Option Explicit

Sub ListOfSquads()
    
    ' Workbook
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    ' Source
    Dim sws As Worksheet: Set sws = wb.Worksheets("Apontamentos")
    Dim stbl As ListObject: Set stbl = sws.ListObjects("Apontamentos")
    Dim slcl As ListColumn: Set slcl = stbl.ListColumns("Área")
    Dim scrg As Range: Set scrg = slcl.Range
    
    ' Destination
    Dim dws As Worksheet: Set dws = wb.Worksheets("Squads")
    dws.Columns("A").ClearContents
    Dim dfCell As Range: Set dfCell = dws.Range("A1")
    
    ' Copy
    scrg.Copy dfCell
 
End Sub