简体   繁体   English

Excel VBA使用动态范围复制和粘贴脚本

[英]Excel VBA copy and paste script using Dynamic Range

I have a data sheet that populates other worksheets within the file based upon an advanced filter I created. 我有一个数据表,该数据表根据我创建的高级过滤器填充文件中的其他工作表。 I only need to copy certain columns from the advanced filter and not the entire filter depending upon the report desired. 我只需要复制高级过滤器中的某些列,而不必复制整个过滤器,这取决于所需的报告。 When the advanced filter brings back nothing (meaning there are no matches for that month) the script is copying and pasting the header instead of copying and pasting nothing. 当高级过滤器未带回任何内容(表示该月没有匹配项)时,脚本将复制并粘贴标题,而不是复制并粘贴任何内容。 Any suggestions on how to avoid copying and pasting the header when the advanced filter brings back no results? 关于在高级过滤器未返回任何结果时如何避免复制和粘贴标头的任何建议? Here is the script for the first worksheet that gets copied: 这是要复制的第一个工作表的脚本:

Sub Populate()

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Data")


sht.Range("A1:S400").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _
    Sheets("Sheet1").Range("A1:S12"), Unique:=False


Set StartCell = sht.Range("G2")
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

   sht.Range(StartCell, sht.Cells(LastRow, "M")).Copy
   Worksheets("OC 2016 - Post-65").Range("A18").PasteSpecial Paste:=xlPasteValues


Sheet3.Columns().AutoFit
Application.CutCopyMode = False

For those who may have a similar problem and want to see how I fixed my problem, I'll post what I edited thanks to Scott's answer above. 对于那些可能有类似问题并且想看看我如何解决问题的人,由于上面的Scott的回答,我将发布经过编辑的内容。 I'm not an expert, so I may have misplaced the If statement but it is working in what I am doing. 我不是专家,所以我可能放错了If语句,但是它正在执行我的工作。

Sub Populate()

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Data")


sht.Range("A1:S400").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _
Sheets("Sheet1").Range("A1:S12"), Unique:=False


Set StartCell = sht.Range("G2")
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

If LastRow > 2 Then

sht.Range(StartCell, sht.Cells(LastRow, "M")).Copy
Worksheets("OC 2016 - Post-65").Range("A18").PasteSpecial Paste:=xlPasteValues

End If

Sheet3.Columns().AutoFit
Application.CutCopyMode = False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM