如何使用 vba 中的输入框选择工作表

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

How do i select worksheet using an inputbox in vba

vbaexcel-vbaexcel

提问by user3793997

I am trying to select a worksheet every time when i open up a workbook using an inputbox in VBA. here is my code for opening a workbook but after i open up my workbook, how do i select a worksheet inside that workbook?

每次我使用 VBA 中的输入框打开工作簿时,我都试图选择一个工作表。这是我打开工作簿的代码,但在我打开工作簿后,如何选择该工作簿中的工作表?

     Sub button7_click()
         dim wb as string
         dim ss as string

           wb = Application.GetOpenFilename
               if wb <> "False" Then Workbooks.Open wb

      End sub

回答by whistler

Assuming "Sheet1" is the name of the sheet that you want to select...

假设“Sheet1”是您要选择的工作表的名称...

Workbooks(wb).Sheets("Sheet1").Select

EDIT: And you can use something like this to get a variable sheet name from an InputBox. In its simplest form...

编辑:您可以使用类似的方法从 InputBox 获取变量表名称。以其最简单的形式...

Dim Result As String

Result = InputBox("Provide a sheet name.")
Workbooks(wb).Sheets(Result).Select

...but I would add some error handling into this also to prevent errors from blanks, misspelled or invalid sheet names.

...但我会在其中添加一些错误处理,以防止出现空格、拼写错误或无效的工作表名称错误。

回答by djikay

Let's say you have a "normal", blank Excel workbook with sheets "Sheet1", "Sheet2" and "Sheet3". Now, when the workbook opens, let's assume you want to activate(not select, as that's different) the sheet called "Sheet2".

假设您有一个“普通”的空白 Excel 工作簿,其中包含工作表“Sheet1”、“Sheet2”和“Sheet3”。现在,当工作簿打开时,假设您要激活(而不是选择,因为这是不同的)名为“Sheet2”的工作表。

In your workbook's ThisWorkbookmodule, add this code:

在您的工作簿ThisWorkbook模块中,添加以下代码:

Private Sub Workbook_Open()

  ActiveWorkbook.Sheets("Sheet2").Activate

End Sub

Make sure this code is pasted inside of the ThisWorkbookobject and not in a Module, Form, or Sheet object.

确保此代码粘贴在ThisWorkbook对象内部,而不是模块、表单或工作表对象中。

Save and exit the workbook. When you re-open it, "Sheet2" will be the active sheet.

保存并退出工作簿。当您重新打开它时,“Sheet2”将成为活动工作表。