vba 如何在vba中打开工作表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3204380/
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-08 10:36:26  来源:igfitidea点击:

How do I open a worksheet in vba?

vbaworksheet

提问by Dr. Thomas C. King

Hilariously the following code only works if the worksheet is actually selected in the excel window. I really want to finish this macro soon but can't seem to work out how to select a specific worksheet so it is open in excel? Many thanks if someone knows how. I have to use range and so on.

有趣的是,以下代码仅在 Excel 窗口中实际选择工作表时才有效。我真的很想尽快完成这个宏,但似乎无法弄清楚如何选择特定的工作表,以便在 excel 中打开它?如果有人知道如何,非常感谢。我必须使用范围等等。

sheet.Range(Cells(firstRow, 2).Address(False, False), Cells(lastRow, 50)).Select
With Selection
    .Copy
End With
sheet.Range(Cells(firstRow, 3).Address(False, False), Cells(lastRow, 51)).Select
With Selection
    .PasteSpecial xlPasteValuesAndNumberFormats
End With

回答by Jay

You can activate the worksheet by name or by 1-based index (the number -- 1st workbook, 2nd, and so on). The syntax is the same, either way.

您可以按名称或按基于 1 的索引(数字 - 第 1 个工作簿、第 2 个工作簿等)激活工作表。无论哪种方式,语法都是相同的。

This will activate the 3rd worksheet:

这将激活第三个工作表:

ActiveWorkbook.Sheets(3).Activate

This will activate the worksheet named stats:

这将激活名为 stats 的工作表:

ActiveWorkbook.Sheets("stats").Activate

Of course, you don't have to actually make the worksheet selected in the Excel window to work with it. Your code uses a variable called sheet, which I assume you've assigned to the active worksheet. Instead of doing that, you can set sheet = ActiveWorkbook.Sheets("stats"), and then work with the sheet even if is not in view.

当然,您不必实际在 Excel 窗口中选择工作表来使用它。您的代码使用了一个名为 的变量sheet,我假设您已将其分配给活动工作表。与其这样做,您还可以set sheet = ActiveWorkbook.Sheets("stats"),然后处理工作表,即使工作表不在视图中。

回答by Andy Robinson

Workbooks(x).Worksheets(x).Activate ?

工作簿(x)。工作表(x)。激活?