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

rfbsl7qr  于 2022-12-20  发布在  其他
关注(0)|答案(3)|浏览(353)

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

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

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

      End sub
wsxa1bj1

wsxa1bj11#

假设“Sheet1”是要选择的图纸的名称...

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

编辑:你可以用类似这样的方法从一个输入框中得到一个变量表名。

Dim Result As String

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

...但我会添加一些错误处理到这也是为了防止错误的空白,拼写错误或无效的工作表名称。

nwlls2ji

nwlls2ji2#

假设您有一个“普通”的空白Excel工作簿,其中包含工作表“Sheet1”、“Sheet2”和“Sheet3”。现在,当工作簿打开时,假设您要 * 激活 *(不是选择,如that's different)名为“Sheet2”的工作表。
在工作簿的ThisWorkbook模块中,添加以下代码:

Private Sub Workbook_Open()

  ActiveWorkbook.Sheets("Sheet2").Activate

End Sub

确保将此代码粘贴到ThisWorkbook对象内部,而不是模块、窗体或工作表对象中。
保存并退出工作簿。重新打开时,“Sheet2”将成为活动工作表。

avwztpqn

avwztpqn3#

下面是最后的代码,如果有人想要的话。多选是不太可能的,因为复制的工作表只复制和增加所选范围的最大值,而不是单独选择的所有单元格。

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

相关问题