vba Excel Marcro - 根据行号删除一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13878022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:48:49  来源:igfitidea点击:

Excel Marcro - delete a row based on row number

excelvba

提问by davidb

please help..i need a macro to delete specific rows based on row number (line number) for example, if i want to delete the the 2nd,9th,20th,150th rows, how it can be done in macro, please provide a macro where i can copy and paste the line numbers in the code and run from module. i have the row numbers in sheet2 Column A which are the rows to be deleted from sheet1

请帮助..我需要一个宏来根据行号(行号)删除特定行,例如,如果我想删除第 2、9、20、150 行,如何在宏中完成,请提供宏,我可以在其中复制和粘贴代码中的行号并从模块运行。我在 sheet2 列 A 中有行号,这些行是要从 sheet1 中删除的行

回答by InContext

for one row:

一行:

Rows(4).Delete Shift:=xlUp

For multiple rows:

对于多行:

Union(Rows(4), Rows(7)).Delete Shift:=xlUp

For your specific case to allow to dynamically delete rows based on a list of row numbers in a source sheet. Change SourceWks to the worksheet where the numbers are stored and deletedWks to the worksheet where the rows are going to be deleted.

对于您的特定情况,允许根据源工作表中的行号列表动态删除行。将 SourceWks 更改为存储数字的工作表,将 DeleteWks 更改为要删除行的工作表。

Dim deleteRows As Range
Dim data() As Variant
Dim i As Double

Dim SourceWks As Worksheet, deleteWks As Worksheet

Set SourceWks = Sheet2
Set deleteWks = Sheet1

    With SourceWks
        data = .Range(.Cells(1, 1), .Cells(1, 1).End(xlDown))
    End With

    Set deleteRows = deleteWks.Rows(data(1, 1))

    For i = 2 To UBound(data, 1)

        Set deleteRows = Union(deleteRows, deleteWks.Rows(data(i, 1)))

    Next i

    deleteRows.Delete Shift:=xlUp