InputBox的工作表选择问题

时间:2014-11-28 06:44:12

标签: excel excel-vba vba

我有一个包含以下代码的Excel VBA文件。我的问题是InputBox无法正常工作。有10张。第一张名为"菜单"。其他片材如片材2-10。片材3,4和5已应用VeryHidden。请帮我纠正它。

Private Sub CommandButton1_Click()
    Dim Sh As Worksheet

    For Each Sh In ThisWorkbook.Worksheets
        If Sh.Name <> "Menu" Then
            Sheet3.Visible = xlSheetVeryHidden
            Sheet4.Visible = xlSheetVeryHidden
            Sheet5.Visible = xlSheetVeryHidden
        End If
    Next Sh

    Dim myList As String
    Dim i As Integer
    Dim mySht

     i = 1
     For Each oSheet In ActiveWorkbook.Sheets
         If oSheet.Visible <> xlSheetVeryHidden Then

            myList = myList & i & " - " & oSheet.Name & " " & vbCr
            i = i + 1
         End If
    Next oSheet

    mySht = InputBox("Select Sheet to go to." & vbCr & myList)
    ActiveWorkbook.Sheets(CInt(mySht)).Select
End Sub

1 个答案:

答案 0 :(得分:0)

就像我在上面的评论中说的那样;问题是Sheets(CInt(mySht))

<强>问题

当您指定一个数字时,请说3,然后代码Sheets(CInt(mySht))变为Sheets(3)。但这不是你想要的。如果您将该数字与" - "连接,然后使用工作表名称,则需要该数字后面的名称。 Sheets(3)实际上可能是指隐藏的工作表,而不是第3张可见工作表,因此您收到错误。

方法

  1. 不使用myList,而是使用数组。
  2. 在用户做出选择后拆分数组,然后转到该表
  3. <强>解决方案

    这是你在尝试的吗?

    Private Sub CommandButton1_Click()
        Dim Sh As Worksheet
        Dim ShName As String
        Dim i As Integer
        Dim mySht, MyAr
    
        For Each Sh In ThisWorkbook.Worksheets
            Sh.Visible = xlSheetVisible
        Next Sh
    
        Sheet3.Visible = xlSheetVeryHidden
        Sheet4.Visible = xlSheetVeryHidden
        Sheet5.Visible = xlSheetVeryHidden
    
        For Each Sh In ThisWorkbook.Worksheets
            If Sh.Visible = xlSheetVeryHidden Then i = i + 1
        Next Sh
    
        ReDim MyAr(1 To ThisWorkbook.Sheets.Count - i)
    
        i = 1
    
        '~~> Store the names of all visible sheets in the array
        For Each Sh In ActiveWorkbook.Sheets
            If Sh.Visible = xlSheetVisible Then
                MyAr(i) = i & " - " & Sh.Name
                i = i + 1
            End If
        Next Sh
    
        '~~> Get user input
        mySht = InputBox("Select Sheet to go to." & vbCr & Join(MyAr, vbNewLine))
    
        If IsNumeric(mySht) Then
            '~~> Get the actual sheet name using split as
            '~~> we had actually appended " - " to it earlier
            ShName = Trim(Split(MyAr(mySht), " - ")(1))
            '~~> Activate the sheet
            ThisWorkbook.Sheets(ShName).Activate
        End If
    End Sub