首页 > 解决方案 > 图片/表格工具不会出现在 Excel 的功能区上

问题描述

我有一个包含图片和表格的工作表。我还有一个用作倒数计时器的用户窗体。用户窗体包含以下代码:

Option Explicit
Const AllowedTime As Double = 10 ' Total time in minutes

Private Sub UserForm_Activate()

Dim T, E, M, S As Double

T = Timer

Do
    E = CDbl(Time) * 24 * 60 * 60 - T
    M = AllowedTime - 1 - Int(E / 60)
    S = 59 - Round((E / 60 - Int(E / 60)) * 60, 0)
    
    TimeLabel.Caption = Format(CStr(M), "00") & ":" & Format(CStr(S), "00")
    
    DoEvents
Loop Until (Timer - T) / 60 >= AllowedTime   

MsgBox "Time Over!"
Unload Me

End Sub

上面的代码不是我的。我在 Excel 论坛上找到了它。它只显示一个 10 分钟的倒数计时器,当时间用完时,用户窗体会卸载。

问题是,当用户窗体运行时,当我单击工作表中的图片或表格时,通常出现在功能区上的图片工具/表格工具没有出现。我插入了一个图表,图表工具也没有出现。

我发现当我通过注释掉上面的计时器代码来运行用户表单时,一切正常。我尝试在 3 台不同的 PC 中打开 Excel 文件,它们都显示了相同的问题。定时器代码有什么问题吗?

标签: excelvbauserform

解决方案


它的发生是因为Do-Loop. 它不仅限于Picture Tools/Table Tools其他菜单,例如PivotTable Tools.

这是一个复制您的问题的示例。当循环运行时,菜单将不会显示。将此代码粘贴到模块中。

Option Explicit

Sub Sample()
    Dim loopCount As Long
    
    Do
        loopCount = loopCount + 1
        
        '~~> Wait for 1 second
        Wait 1
        
        If loopCount > 15 Then Exit Sub
    Loop
End Sub

Private Sub Wait(ByVal nSec As Long)
    nSec = nSec + Timer
    While nSec > Timer
        DoEvents
    Wend
End Sub

Application.OnTime您可以使用来显示计时器,而不是使用循环。这是一个例子。顺便说一句,在 VBA 中也有用于处理计时器的 API。

注意

在使用或测试计时器之前,请备份您的数据或使用新的工作簿。

用户表单代码:

插入一个新的用户表单。让我们称之为frmTimer。贴上一个标签。让我们称之为TimeLabel。现在将此代码粘贴到用户表单中。

Option Explicit

Dim nextMoment As Date

Private Sub UserForm_Activate()
    Timer_Event
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Timer_Stop
End Sub

Sub Timer_Event()
    nextMoment = Now + TimeValue("00:00:01")
    Application.OnTime nextMoment, "Module1.OnTimer"
End Sub

Sub Timer_Stop()
    Application.OnTime nextMoment, "Module1.OnTimer", Schedule:=False
End Sub

Public Sub OnTimer()
    TimeLabel.Caption = Time
    Timer_Event
End Sub

模块代码:

插入一个模块。让我们称之为Module1。(如果这是一个新工作簿,这应该是默认名称)。将此代码粘贴到那里

Option Explicit

Sub OnTimer()
    frmTimer.OnTimer
End Sub

Sub ShowForm()
    frmTimer.Show vbModeless
End Sub

现在运行Sub ShowForm()。您会看到菜单现在没有消失。

在行动

在此处输入图像描述


推荐阅读