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

时间:2014-07-15 18:51:11

标签: vba excel-vba excel

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

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

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

      End sub

3 个答案:

答案 0 :(得分:0)

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

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

编辑:你可以使用这样的东西从InputBox中获取一个可变的工作表名称。最简单的形式......

Dim Result As String

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

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

答案 1 :(得分:0)

让我们假设您有一张正常的&#34;空白Excel工作簿,其中包含工作表&#34; Sheet1&#34;,&#34; Sheet2&#34;和&#34; Sheet3&#34;。现在,当工作簿打开时,让我们假设您要激活(而不是选择that's different)名为&#34; Sheet2&#34;的表格。

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

Private Sub Workbook_Open()

  ActiveWorkbook.Sheets("Sheet2").Activate

End Sub

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

保存并退出工作簿。当你重新打开它时,&#34; Sheet2&#34;将是活动表。

答案 2 :(得分:0)

如果有人想要,这里是最终代码。 多项选择不太可能,因为复制的工作表只复制并递增所选范围的最大值,而不是单独选择的所有单元格....

Sub CopyAndIncrement()
Dim ws As Worksheet
Dim Count As Integer
Dim Rng As Range
Dim myValue As Integer
Dim wsName As String


wsName = InputBox("Provide the EXACT sheet name you want to copy.")
'error handling loop for Worksheet name
For p = 1 To Worksheets.Count
    If Worksheets(p).Name = wsName Then
        exists = True
    End If
Next p
   
  If Not exists Then
    While exists = False
     wsName = InputBox("Sheet not found re-enter name.")
        For p = 1 To Worksheets.Count
            If Worksheets(p).Name = wsName Then
            exists = True
            End If
        Next p
    Wend
  End If

Set Rng = Application.InputBox( _
  Title:="Increment your worksheet", _
  Prompt:="Select a cell(s) you want to increment", _
  Type:=8)
On Error GoTo 0
If Rng Is Nothing Then Exit Sub 'Test to ensure User Did not cancel

'Set Rng = Rng.Cells(1, 1) 'Set Variable to first cell in user's input (ensuring only 
'1 cell) >> commenting this can give multiple selections
 
 myValue = InputBox("How many time do you want it to increment? Give me the number ")
  
    Do While Count < myValue
      
      For Each ws In Worksheets   ' this loop selects the last sheet in the workbook
          LastWs = ws.Name
          i = ws.Range(Rng.Address).Value
          If i > j Then
              j = i
          End If
      Next
      
    Sheets(wsName).Select
    Sheets(wsName).Copy After:=Sheets(LastWs)
    ActiveSheet.Range(Rng.Address).Value = j + 1
    Count = Count + 1
    Loop
    End Sub