用户窗体命令按钮代码 - 错误 91:未设置对象变量或块变量

UserForm command button code - Error 91: Object variable or With block variable not set

我的命令按钮单击事件代码一直抛出错误 91。当我单步执行代码时,它会在 'Set findvalue' 代码执行后立即抛出错误。请参阅下面的代码片段。我无法通过检查代码本身来弄清楚。

'findvalue' 被标注为范围对象。 'DataSH' 是主数据 table 所在的工作表,以记录 ID 列(B 列)开头。用户表单元素在 DataSH 上的数据 table 中设置为它们各自的列。

    Private Sub cmdEdit_Click()
    'declare the variables
    Dim findvalue As Range
    Dim cNum As Integer
    Dim DataSH As Worksheet
    'error handling
    On Error GoTo errHandler:
    'hold in memory and stop screen flicker
    Application.ScreenUpdating = False
    Set DataSH = Sheet1

获取此代码段的点击事件子例程被设置为根据这些 UF 元素中的值(即更改或删除的值)。重点是使用 UF 元素(文本框和组合框)中所做的任何更改更新 DataSH 上的主数据 table。

    Set findvalue = DataSH.Range("B:B"). _
    Find(What:=Me.tbRecID.Value, LookIn:=xlValues, LookAt:=xlWhole)
    'update the values
    findvalue = tbRecID.Value
    findvalue.Offset(0, 1) = tbRecDate.Value
    findvalue.Offset(0, 2) = cmbRecLoc.Value
    findvalue.Offset(0, 3) = cmbRecCust.Value
    findvalue.Offset(0, 4) = tbRecAmt.Value
    findvalue.Offset(0, 5) = cmbRecComm.Value
    findvalue.Offset(0, 6) = cmbRecPrin.Value
    findvalue.Offset(0, 7) = tbRecTerr.Value
    findvalue.Offset(0, 8) = tbRecRep.Value

弹出错误 91(在这种情况下),因为您试图将值分配给某个尚未设置的范围,所以您的 Me.tbRecID.Value 不存在于 DataSH.Range("B:B") 中。为了避免这个问题,你可以添加一些错误异常,例如:

    Set findvalue = DataSH.Range("B:B"). _
    Find(What:=Me.tbRecID.Value, LookIn:=xlValues, LookAt:=xlWhole)
    'update the values
On Error GoTo ErrHand:
    findvalue = tbRecID.Value
On Error GoTo 0
    findvalue.Offset(0, 1) = tbRecDate.Value
    findvalue.Offset(0, 2) = cmbRecLoc.Value
    findvalue.Offset(0, 3) = cmbRecCust.Value
    findvalue.Offset(0, 4) = tbRecAmt.Value
    findvalue.Offset(0, 5) = cmbRecComm.Value
    findvalue.Offset(0, 6) = cmbRecPrin.Value
    findvalue.Offset(0, 7) = tbRecTerr.Value
    findvalue.Offset(0, 8) = tbRecRep.Value
ErrHand:
[rest of your code]

如果没有为该变量分配范围,这将强制程序绕过使用 findvalue 的行。

您的代码根本无法在 "DataSH.Range("B:B") 中找到 "Me.tbRecID.Value"""

因此,如果 findvalue 已实际设置为有效范围

,则将代码包装在 "If Then End If" 中执行
Set findvalue = DataSH.Range("B:B"). _
Find(What:=Me.tbRecID.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not findvalue Is Nothing Then
    findvalue.Offset(0, 1) = tbRecDate.Value
    findvalue.Offset(0, 2) = cmbRecLoc.Value
    findvalue.Offset(0, 3) = cmbRecCust.Value
    findvalue.Offset(0, 4) = tbRecAmt.Value
    findvalue.Offset(0, 5) = cmbRecComm.Value
    findvalue.Offset(0, 6) = cmbRecPrin.Value
    findvalue.Offset(0, 7) = tbRecTerr.Value
    findvalue.Offset(0, 8) = tbRecRep.Value
End If

我认为 DataSH 没有设置。 "Sheet1" 是 sheet 的名称还是工作 sheet 变量?如果它是一个名称,那么您必须像这样设置 DataSH :

Set DataSH = thisworkbook.worksheets("Sheet1") 

而不是Set DataSH = Sheet1