gpt4 book ai didi

excel - ErrorHandler 不工作 -> 编译错误/找不到对象

转载 作者:行者123 更新时间:2023-12-04 22:29:17 26 4
gpt4 key购买 nike

我创建了一个带有几个 activeX 元素的 excelfile。到目前为止,该文件正在按预期工作,现在我正在解决日常业务中可能发生的“用户错误”。
以后使用 activeX 元素(Toggle-、Command- 和 SpinButtons)非常重要,所以我创建了一些子元素来恢复每个元素。他们正在按预期工作。

问题:现在如果有人删除了一个按钮怎么办?我尝试使用 If-Statements(如果 >element< 什么都不是……),但它没有用。下一个方法是“On Error GoTo”。
因此,我构建了一个 ErrorHandler 并作为常规代码按预期工作。处理程序创建一个具有所需名称的 SpinButton。如果我在代码中构建错误(a = 1/0),则处理程序正在完成他的工作,但这只是“体外”。

在 vivo 中,如果我想要的 >element< 不存在,我的代码会以错误结束(编译 error_ 方法或找不到对象),但我的处理程序什么也不做,尽管这是它的唯一目的。

我的代码:

Sub Cal_SpinButton_Nr()
Subroutine:
On Error GoTo CreateObject:
With Tabelle5.SpinButton_Nr
.Left = 198
.Height = 65.25
.Top = 1.5
.Width = 54.75
.Orientation = fmOrientationVertical
.BackColor = &H8000000F
.ForeColor = &H80000012
End With

Exit Sub
CreateObject:
Tabelle5.OLEObjects.Add("Forms.SpinButton.1").Name = "SpinButton_Nr2"
'Resume Subroutine
End Sub

Option Explicit 已打开,并且 sub 不包含任何变量。只要有一个对象(SpinButton_Nr)它就可以工作。没有对象我得到一个编译错误。

“恢复子程序”现在被静音以避免无限循环(我通过首先静音“退出子程序”并按 F5 来吸取教训...),常规功能是再次触发相同的子程序以便将新对象放入正确的地方。
出于(“体外”)测试的原因,新对象被称为_Nr2,后来它只是_Nr。

现在的问题是:为什么“on error”语句没有涵盖编译错误?如何修改代码才能正常工作?

语法应该是“如果 >element< 存在,则设置属性,如果 <element> 不存在,则创建它并在之后设置属性。

最佳答案

我建议如下:

因此,如果在开始格式化之前不创建旋转按钮,您实际上会测试它是否存在。在您的过程中没有奇怪的错误处理和 goto 跳转。

Option Explicit

Sub Cal_SpinButton_Nr()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Tabelle5") '<-- tab name
'OR
'Set ws = Tabelle5 '<-- VBA code name

Dim SpinBtn As Object
On Error Resume Next 'next line errors if no spinbutton exists
Set SpinBtn = ws.OLEObjects("SpinButton_Nr")
On Error Goto 0 'always re-activate error reporting!

'if no spinbutton is found create it before formatting starts
If SpinBtn Is Nothing Then
Set SpinBtn = ws.OLEObjects.Add("Forms.SpinButton.1")
SpinBtn.Name = "SpinButton_Nr"
End If

'format spin button
With SpinBtn
.Left = 198
.Height = 65.25
.Top = 1.5
.Width = 54.75

'not that for these .Object is necessary because of using .OLEObjects("SpinButton_Nr")
.Object.Orientation = fmOrientationVertical
.Object.BackColor = &H8000000F
.Object.ForeColor = &H80000012
End With
End Sub

关于excel - ErrorHandler 不工作 -> 编译错误/找不到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54671525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com