我想直接在工作表上创建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
Run Code Online (Sandbox Code Playgroud)
问题是:在代码执行结束时,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
Run Code Online (Sandbox Code Playgroud)
...但是,如果我添加行:
testEnter
DoEvents
testExit
Run Code Online (Sandbox Code Playgroud)
......到我的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
Run Code Online (Sandbox Code Playgroud)
也无法使用 F8 单步执行