【问题标题】:Pasting under original data at the bottom of the column in VBA在VBA中的列底部粘贴原始数据
【发布时间】:2020-09-11 20:13:45
【问题描述】:

我正在尝试将数据从一张纸复制并粘贴到另一张纸上,但在当前数据下。粘贴的目的地会有所不同,因为我希望将其粘贴到已经在该范围内的最后一行数据的下方。我首先过滤原始表中的数据,将其复制并粘贴到目标表中。 例如,我希望将原始工作表中的新数据(B2:D 和 lastrow)粘贴到目标工作表中当前数据下方的列(G:I 和 newlastrow)中。

我已经尝试了以下方法,但目前我遇到了范围问题。

Sub copytoderiv()

Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
ActiveWorkbook.Sheets("origin").Activate
Call TURNFILTERSOFF


Sheets("origin").Range("$A$1:$D$50000").AutoFilter Field:=1, Criteria1:="XXX"
        
ActiveSheet.Range("B2:D" & lastrow).SpecialCells(xlCellTypeVisible).Copy
    
Dim Newlastrow As String
ActiveWorkbook.Sheets("destination").Activate
Newlastrow = ActiveSheet.Cells(Rows.Count, "H").End(xlUp).Row + 1
Range("G:I" & Newlastrow).Select
ActiveSheet.PasteSpecial
 
Call TURNFILTERSOFF
    
    
    
End Sub

【问题讨论】:

  • "G:I" & Newlastrow 不是有效的范围引用。
  • 我明白了,我将 newlastrow 更改为 long 并将范围更改为 Range("G2:I" & Newlastrow) 现在它粘贴在右侧列中,但覆盖了 G2 顶部的当前数据,而不是当前数据下方数据
  • ...因为您在想使用Newlastrow 时包含了2?
  • Range("G" & Newlastrow).Select 但你真的是should avoid using Select。
  • 代码是位于ActiveWorkbook 还是其他工作簿中?我们可以假设TURNFILTERSOFF 是一个正常工作的过程吗?

标签: excel vba


【解决方案1】:

Copy 与 Autofilter 和 SpecialCells

链接(微软)

快速修复

Option Explicit

Sub copytoderiv()

    ' Define Workbook.  
    Dim wb As Workbook
    Set wb = ThisWorkbook ' The worksheet containing this code.
    
    ' Define Original Worksheet and its Last Row.
    Dim orig As Worksheet: Set orig = wb.Worksheets("origin")
    Dim LastRow As Long
    LastRow = orig.Cells(orig.Rows.Count, "A").End(xlUp).Row
    
    ' Define Destination Worksheet and its Start Row.
    Dim dest As Worksheet: Set dest = wb.Worksheets("destination")
    Dim StartRow As String
    StartRow = dest.Cells(dest.Rows.Count, "H").End(xlUp).Row + 1
    
    orig.Activate
    TURNFILTERSOFF
    
    ' Filter data.
    orig.Range("A1:D" & LastRow).AutoFilter Field:=1, Criteria1:="XXX"
    
    ' Either:
    ' Copy values and formats.
    orig.Range("B2:D" & LastRow).SpecialCells(xlCellTypeVisible).Copy _
      dest.Range("G" & StartRow)
    
    ' Or:
    ' Copy values, formulas and formats.
'    orig.Range("B2:D" & LastRow).SpecialCells(xlCellTypeVisible).Copy
'    'Study the PasteSpecial method thorrowly because there are many options.
'    dest.Range("G" & StartRow).PasteSpecial
'    Application.CutCopyMode = False
     
    TURNFILTERSOFF
    
End Sub

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 2016-07-11
    • 2023-03-29
    • 2017-10-12
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多