使用userform和listbox运行宏后无法关闭工作簿

时间:2014-06-07 08:00:40

标签: excel excel-vba vba

我正在使用下面的代码更轻松地浏览工作簿。但是,运行宏光标后运动是奇数(限制范围和跳跃)。此外,单击红色" x"时,工作簿不会关闭。关上窗户。此外,组和取消组合图标(用于隐藏或扩展行和列)不起作用。似乎以某种方式"控制"仍然在VBA中应该是正常的Excel。所有帮助都非常感谢。

用户形式代码:

Option Explicit
Option Base 1

Private Sub UserForm_Initialize()
    Dim ShList()
    Dim ShCount As Integer
    Dim x As Integer
    Dim ListPos As Integer

    ShCount = ActiveWorkbook.Sheets.Count
    ReDim Preserve ShList(1 To ShCount)

    For x = 1 To ShCount
        If Sheets(x).Name = ActiveSheet.Name Then
            ListPos = x - 1
        End If
        ShList(x) = Sheets(x).Name
    Next x

    With ListBox1
        .List = ShList
        .ListIndex = ListPos
    End With

End Sub

Private Sub CommandButton1_Click()
    Sheets(ListBox1.Value).Activate
    Unload UserForm1
End Sub

点击按钮激活代码:

Option Explicit

Sub WorksheetSelect_Click()
    UserForm1.Show
End Sub

3 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,不得不删除以下代码: 片材(1).Activate

删除后,我可以一如既往地关闭Excel。

答案 1 :(得分:0)

我遇到了同样的问题。它是通过将活动工作表上任何单元格中的任何单元格值更改为我的VBA代码中的最后一行来解决的。在我的情况下,我添加了VBA代码:范围(" A1")=" _",但您也可以将任何其他单元格更改为任何其他值。

答案 2 :(得分:-1)

抱歉不使用评论,因为它太长了,只是分析你的代码

Option Explicit
Option Base 1 'someone tell me what's this ? i might be noob at this point

Private Sub UserForm_Initialize()
Dim ShList() 'as variant
Dim ShCount As Integer 'as Long
Dim x As Integer 'as long
Dim ListPos As Integer 'as Long

ShCount = ActiveWorkbook.Sheets.Count 
ReDim Preserve ShList(1 To ShCount) 'remove preserve

For x = 1 To ShCount
    If Sheets(x).Name = ActiveSheet.Name Then
        ListPos = x - 1
    End If
    ShList(x) = Sheets(x).Name
Next x

With ListBox1 'i usually write : with Me.Listbox1, but i guess its ok
    .List = ShList
    .ListIndex = ListPos
End With

'add erase ShList (free memory)
End Sub

如此重要,删除Preserve,并为数组添加一个Erase