简体   繁体   English

在excel vba中的特定工作表中选择范围

[英]Select range in a particular sheet in excel vba

I have a question about selecting a range in a particular sheet using excel vba.我有一个关于使用 excel vba 在特定工作表中选择范围的问题。

I don't know why the following is not working:我不知道为什么以下不起作用:

Thisworkbook.Sheets("N&A").Range("B4:F16").select

However this works:但是,这有效:

Thisworkbook.Sheets("N&A").Activate
ActiveSheet.Range("B4:F16").Select

The VBA code is programmed on "N&A" sheet. VBA 代码在“N&A”表上编程。

Could anyone let me know what could be the reason?谁能让我知道可能是什么原因?

Thank you!谢谢!

You've basically answered your own question.你基本上已经回答了你自己的问题。 Here's an excerpt from Excel 2003 help :这是Excel 2003 帮助的摘录:

"If you use the Select method to select cells, be aware that Select works only on the active worksheet. If you run your Sub procedure from the module, the Select method will fail unless your procedure activates the worksheet before using the Select method on a range of cells." “如果您使用 Select 方法选择单元格,请注意 Select 仅适用于活动工作表。如果您从模块运行 Sub 过程,除非您的过程在使用 Select 方法之前激活工作表,否则 Select 方法将失败细胞范围。”

More importantly, remember that it's rarely necessary to use Select in VBA, and it should be avoided if possible .更重要的是,请记住在 VBA 中很少需要使用Select ,并且应该尽可能避免使用它。

You can try with following code to aviod acriveworksheet:您可以尝试使用以下代码来避免 acriveworksheet:

Sub Clean()


lastrow = Worksheets("REPORT").Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row

Dim ws As Worksheet
Set ws = Worksheets("Report")
Set rng = ws.Cells(1, 1)
With ws
    Set rng = .Range(.Cells(2, 1), .Cells(lastrow, 5))
End With

rng.Clear

End Sub

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

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