excel - 除非手动切换设计模式,否则工作表上容器框架中的表单对象处于非活动状态
问题描述
我想直接在工作表上创建 ActiveX 对象。我可以以编程方式做到这一点。
我还想要几个与特定背景组合在一起的控件。我在 Frame 对象中创建它们:即控件将是框架的“子对象”。
以下示例代码完成了这项工作:
Sub CreateFormOnSheet()
With ActiveSheet
' Add the frame background:
.OLEObjects.Add(ClassType:="Forms.Frame.1", Left:=10, Top:=10, Width:=300, Height:=300).Name = "container_frame"
With .OLEObjects("container_frame")
With .Object
.Caption = "This is the frame caption"
.BackColor = RGB(150, 0, 100)
.BorderColor = RGB(255, 255, 255)
.Controls.Add("Forms.CommandButton.1").Name = "MyButton"
With .Controls("MyButton")
.Left = 10
.Top = 10
.Width = 100
.Height = 50
.BackColor = RGB(0, 0, 100)
.ForeColor = RGB(255, 255, 255)
.Caption = "My Button"
.FontName = "Arial"
.Font.Bold = True
.Font.Size = 10
.WordWrap = True
End With
End With
End With
End With
End Sub
问题是:在代码执行结束时,MyButton 的行为就像它被“锁定”或禁用一样。用户不能点击它。没有伴随 CommandButton 对象的那种“按钮按下”动画。
添加.Enabled = True
并不能解决此问题。它已经启用,它就像没有启用一样。
如果我手动进入“设计模式” - 然后再次退出 - 按钮启用。
我发现了如何以编程方式启用/禁用设计模式:
Sub testEnter()
EnterExitDesignMode True
End Sub
Sub testExit()
EnterExitDesignMode False
End Sub
Sub EnterExitDesignMode(bEnter As Boolean)
Dim cbrs As CommandBars
Const sMsoName As String = "DesignMode"
Set cbrs = Application.CommandBars
If Not cbrs Is Nothing Then
If cbrs.GetEnabledMso(sMsoName) Then
If bEnter <> cbrs.GetPressedMso(sMsoName) Then
cbrs.ExecuteMso sMsoName
Stop
End If
End If
End If
End Sub
...但是,如果我添加以下行:
testEnter
DoEvents
testExit
...到我的 Sub 结束时,问题仍然存在。即使它有效,这似乎也是一种黑客行为。我宁愿了解这里发生了什么,并应用适当的解决方案。
解决方案
我认为这是添加 OLEObjects 的一个已知问题,解决方法是在不可见和可见之间切换。在这种情况下为您的框架。(或上面评论中提到的方法)
Sub CreateFormOnSheet()
With ActiveSheet
' Add the frame background:
.OLEObjects.Add(ClassType:="Forms.Frame.1", Left:=10, Top:=10, Width:=300, Height:=300).Name = "container_frame"
With .OLEObjects("container_frame")
With .Object
.Caption = "This is the frame caption"
.BackColor = RGB(150, 0, 100)
.BorderColor = RGB(255, 255, 255)
.Controls.Add("Forms.CommandButton.1").Name = "MyButton"
With .Controls("MyButton")
.Left = 10
.Top = 10
.Width = 100
.Height = 50
.BackColor = RGB(0, 0, 100)
.ForeColor = RGB(255, 255, 255)
.Caption = "My Button"
.FontName = "Arial"
.Font.Bold = True
.Font.Size = 10
.WordWrap = True
End With
End With
.Visible = False 'toggle the Frame
.Visible = True
End With
'or Sheets(1).Activate
'or .Activate
End With
End Sub
也无法使用 F8 单步执行
推荐阅读
- python - google-api-python-client 1.9.3 的重大更改 - AttributeError:模块 'google.api_core' 没有属性 'gapic_v1'
- vb.net - 显示 Telnet 客户端收到的消息时的延迟
- laravel - 如何更改 laravel 文件路径”?
- c# - 用值初始化字典(C#)
- python - 正则表达式在所有标点符号和英文字符序列处拆分,并在 Python 中使用注音保留分隔符
- javascript - 获取 HTML 内容下的 href 列表
- python - 有没有办法在网站上嵌入使用 python 的 Networkx 包的图形代码,以便输出可以直接显示在网站上?
- r - 利用回收将不同长度的列表转换为数据帧的功能
- node.js - 导出的函数在另一个文件 nodejs 中不起作用
- ios - 如何从函数内部获取文本字段的文本?