Excel VBA命令按钮代码无法识别对象变量

时间:2017-06-12 04:03:38

标签: excel vba excel-vba userform

我为命令按钮编写了以下代码,将UserForm的(文本)内容添加到现有(命名)动态范围" MasterTable":

Private Sub AddDev_Click()

    Application.CutCopyMode = False

    With Worksheets("Table").Range("MasterTable").ListObject.ListRows.Add
         .Offset(1, 0).Value = NewDevRecord.NewCorp.Value
         .Offset(1, 1).Value = NewDevRecord.NewAddr.Value
         .Offset(1, 1).Value = NewDevRecord.NewFac.Value
    End With

End Sub

当我填充for并点击该按钮时,它会抛出Error 91- Object Variable or With Block Variable Not Set并突出显示Worksheets("Table").Range("MasterTable")作为违规者。这不是引用范围的有效方法吗?它适用于我的vba book和sheet模块 - UserForm组件没有访问权限吗?我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果MasterTable已创建为ListObject,那么您可以将其称为:

Worksheets("Table").ListObjects("MasterTable")

所以这段代码可行:

Private Sub AddDev_Click()

    Application.CutCopyMode = False

    With Worksheets("Table").ListObjects("MasterTable").ListRows.Add
         .Offset(1, 0).Value = NewDevRecord.NewCorp.Value
         .Offset(1, 1).Value = NewDevRecord.NewAddr.Value
         .Offset(1, 1).Value = NewDevRecord.NewFac.Value
    End With

End Sub