Excel Userform列表框 - 命名范围自动化错误

时间:2017-09-18 09:59:27

标签: excel excel-vba listbox named-ranges vba

我使用动态命名范围“Unit”作为userform上列表框的rowsource。我使用Userform_Initialize事件而不是列表框的poperties将列表框的rowsource设置为命名范围。

当我修改命名区域中的值时,如果我将rowsource重置为命名区域,则列表框会正确更新以显示修改后的值。

Me.lbUnits.RowSource = "Unit"

当我将新记录从Userform上的文本框传递到命名范围时,命名范围包含新数据。如果我卸载并显示用户表单,则新数据将显示在列表框中。但是我不想卸载/显示用户表单,而只是想刷新列表框。如果我尝试将listbox rowsource刷新到命名范围,我会收到以下运行时错误;

“自动化错误。调用的对象已与其客户端断开连接。”

为了刷新我正在使用的列表框

Me.lbUnits.RowSource = "Unit"

我已经尝试禁用应用程序事件,清除列表框,在将vbNullString设置回命名范围之前将其设置为rowsource。代码

Option Explicit
Dim cNum As Integer
Dim x As Integer
Dim nextRow As Range


Private Sub UserForm_Initialize()

'   Units of Measure
Me.lbUnits.RowSource = "Unit"

End Sub


Private Sub cmbUMAdd_Click()

On Error GoTo errHandler:

'   Number of controls to loop thro
cNum = 3
Set nextRow = Sheet2.Cells(Rows.Count, 5).End(xlUp).Offset(1, 0)

'   Insert Unit of Measure into db
nextRow = Range("Next_UM_ID")
Set nextRow = nextRow.Offset(0, 1)
For x = 2 To cNum
    nextRow = Me.Controls("tbUM" & x).Value
    Set nextRow = nextRow.Offset(0, 1)
Next

'   Refresh the Unit of Measure listbox
Me.lbUnits.RowSource = "Unit"
MsgBox "Unit of Measure details added to database", vbInformation + vbOKOnly

'   Error handler
On Error GoTo 0
Exit Sub

errHandler::
    MsgBox "An Error has Occured " & vbCrLf & "The error number is : " _
    & Err.Number & vbCrLf & Err.Description & vbCrLf & _
    "Please notify the administrator"

End Sub

0 个答案:

没有答案
相关问题