如何防止excel宏粘贴空行

时间:2013-07-28 21:06:56

标签: excel vba excel-vba autofilter

我正在尝试在Excel 2007中设计一个宏。以下是我需要它做的事情:

当我在特定单元格中输入ID并运行宏时,它将在不同工作簿和自动过滤器的A列中搜索该ID。然后我需要它来复制该数据并将其粘贴到第一个工作簿中。我的代码正在运行,但是当它在我的数据下面粘贴了大量额外的行时。我怎样才能使它只复制和粘贴数据而不是空行?这是我的代码:

Sub Medications()
    '
    ' Medications Macro
    '
    ' Keyboard Shortcut: Ctrl+m
    '

    Range("B1").Select
    Workbooks.Open Filename:= _
        "I:\Pharmacy\MTMP\2013\Master Lists\CMR Medication List.xlsx"
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "Member ID"
    Range("A1").Select
    Selection.AutoFilter
    ActiveSheet.Range(Selection, ActiveCell.SpecialCells(xlLastCell)).AutoFilter Field:=1, Criteria1:=Workbooks("Standardized Format Spreadsheet.xlsm").Worksheets("Demographics").Range("B1").Value
    Cells.Select
    Selection.Copy
    Windows("Standardized Format Spreadsheet.xlsm").Activate
    Sheets("Detailed Medication List").Select
    Range("A1").Select
    ActiveSheet.Paste
    Windows("CMR Medication List.xlsx").Activate
    Application.CutCopyMode = False
    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
    Sheets("Demographics").Select
End Sub

2 个答案:

答案 0 :(得分:0)

最好尽量避免选择项目。您可以使用将工作簿设置为对象并通过它访问它。

复制/粘贴时获取额外单元格的原因是您选择每个单元格然后复制。我建议只使用使用的范围,这样你就不会拿起任何额外的细胞。

Sub Medications()
    Dim CMR_Wkbk As Workbook
    Dim SFS_Wkbk As Workbook

    Set SFS_Wkbk = Workbooks("Standardized Format Spreadsheet")
    Set CMR_Wkbk = Workbooks.Open("I:\Pharmacy\MTMP\2013\Master Lists\CMR Medication List.xlsx")

    Range("A1").Value = "Member ID"
    ActiveSheet.UsedRange.AutoFilter Field:=1, Criteria1:=SFS_Wkbk.Sheets("Demographics").Range("B1").Value
    ActiveSheet.UsedRange.Copy Destination:=SFS_Wkbk.Sheets("Detailed Medication List").Range("A1")

    Application.DisplayAlerts = False
    CMR_Wkbk.Close
    Application.DisplayAlerts = True

    Sheets("Demographics").Select
End Sub

答案 1 :(得分:0)

Cells.Select
Selection.Copy

Cells.Select正在选择工作表的全部内容。显然,我不知道你的表格是什么样的,但是只选择CurrentRegion - 相当于单击一个单元格时按下Ctrl-A突出显示的内容:

ActiveCell.CurrentRegion.Copy
相关问题