VBA - 删除另一个工作表中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20206671/
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
VBA - Delete rows in another worksheet
提问by HattrickNZ
Function DeleteRows()
Dim wb As Workbook
Set wb = Workbooks(ThisWorkbook.Name)
Debug.Print wb.Name
Dim wsName As String
Dim ws As Worksheet
wsName = "SheetX"
Set ws = wb.Worksheets(wsName)
Debug.Print ws.Name
With ws
Debug.Print "ws.name = " & ws.Name
Rows("3:31").Select
Selection.Delete Shift:=xlUp
End With
End Function
I have this function, DeleteRows, that deletes the the rows 3:31 from the worksheet "SheetX".
我有这个函数 DeleteRows,它从工作表“SheetX”中删除 3:31 的行。
This only works when "SheetX" is the sheet that is displayed on the screen.
这仅在“SheetX”是显示在屏幕上的工作表时有效。
I want it to work when another sheet, lets say "SheetY", in the workbook is displayed. How can I do this?
我希望它在工作簿中显示另一张工作表时工作,比如说“SheetY”。我怎样才能做到这一点?
One way would be to: 1-activate "SheetY" 2-delete the rows 3-activate "SheetX"
一种方法是:1-激活“SheetY” 2-删除行 3-激活“SheetX”
But this would not be transparent to the user. Appreciate the help.
但这对用户来说是不透明的。感谢帮助。
回答by tigeravatar
You should always try to avoid Select statements. They are almost always unnecessary. That function should be a Sub (because it doesn't have an output) and can be rewritten as a one-liner:
您应该始终尽量避免使用 Select 语句。它们几乎总是不必要的。该函数应该是一个 Sub(因为它没有输出)并且可以重写为一个单行:
Sub DeleteRows()
ThisWorkbook.Sheets("SheetX").Range("3:31").Delete xlUp
End Sub