0

运行 VBA 宏,有时效果很好。但在某些情况下,我收到以下错误。

在此处输入图像描述

我已经调试了代码,但没有收到任何错误。代码如下。

Public Sub Adjust_ComboBox()
On Error GoTo Adjust_ComboBox_Err

    Dim mes As Form
    Set mes = [Form_Treatment Details]


    Dim count As Long
    On Error Resume Next
    For Each ctl In mes.Detail.Controls
        If TypeName(ctl) = "ComboBox" Then
            Dim comboitems() As Variant
            count = 1
            comboitems = ctl.Value
            count = UBound(comboitems) + 1
            ctl.Height = (300 * count)
            Erase comboitems
        End If
    Next


Adjust_ComboBox_Exit:
    Exit Sub

Adjust_ComboBox_Err:
    MsgBox Error$
    Resume Adjust_ComboBox_Exit

End Sub

怎么可能得到这个错误?

4

1 回答 1

0

这整个代码块对我来说看起来很奇怪。

Dim comboitems() As Variant
count = 1
comboitems = ctl.Value
count = UBound(comboitems) + 1
ctl.Height = (300 * count)
Erase comboitems

我的问题是:

  • 为什么要在一个循环中对组合项进行 DIMing 和 ERASEing?
  • 为什么要将数组设置为控件的值?
  • 您是否尝试根据项目数设置高度?
  • 为什么要count=1在两行后才被覆盖时进行设置?

如果我猜对了问题的答案,我认为您可以通过精简循环代码并使用 ListCount 来消除一些可能的崩溃:

count = ctl.ListCount
if count > 0 then
    ctl.Height = (300 * count)
else
    ctl.Height = 300
end if
于 2018-05-11T16:53:28.157 回答