【问题标题】:Why am I getting run time error 91 with my code?为什么我的代码会出现运行时错误 91?
【发布时间】:2020-11-11 01:08:37
【问题描述】:

当我尝试运行此代码时,我收到错误“运行时错误'91':对象变量或未设置块变量”我是 VBA 新手,所以我不太清楚问题出在哪里。我相信它与“Dim currentrow as string”行有关,因为我知道我必须声明变量,但我似乎无法弄清楚问题是什么。你有什么想法?提前致谢。

Private Sub UpdateButton_Click()

Dim currentrow As String

currentrow = Range("A:A").Find(DatabaseEntry.textbox1.Value).Row

 If Me.textbox1.Value = "" Then
 Msgbox "Run number cannot be blank", vbExclamation, "No"
 Exit Sub
 End If

 answer = Msgbox("Are you sure you want to update the record?", vbYesNo 
 + vbQuestion, "UpdateRecord")
 If answer = vbYes Then

 Cells(currentrow, 1) = textbox1.Value
 Cells(currentrow, 2) = textbox2.Value

 End If

 End Sub

【问题讨论】:

  • 什么是DatabaseEntry?此外,currentrow 应该是 Long,而不是 String。
  • DatabaseEntry 是电子表格的名称
  • 实际的工作表对象名称是DatabaseEntry,还是只是工作表的名称?因为如果您没有在编辑器中更改对象名称,则需要将其写为Worksheets("DatabaseEntry")。
  • 抱歉,我说错了。 DatabaseEntry 是用户窗体的名称..

标签: excel vba variables runtime-error


【解决方案1】:

每当您执行查找时:

  • 指定任何其他会影响结果的参数,除了要找到的值
  • 在尝试访问(例如)行之前检查您是否确实得到了匹配

像这样:

Private Sub UpdateButton_Click()

    Dim f As Range, v

    v = Trim(Me.textbox1.Value)
    
    If Len(v) = 0 Then
         Msgbox "Run number cannot be blank", vbExclamation, "No"
         Exit Sub
    End If

     Set f = ActiveSheet.Range("A:A").Find(what:=v, _
                                          lookat:=xlWhole)
     If Not f Is Nothing Then
         if Msgbox("Are you sure you want to update the record?", _
                      vbYesNo + vbQuestion, "UpdateRecord") = vbYes Then
     
    
              With f.EntireRow
                  .Cells(1) = v  'really no need for this
                  .Cells(2) = textbox2.Value
              End With
          End If
     Else
         Msgbox "not found - '" & v & "'"
     End If

 End Sub

【讨论】:

  • 谢谢!!我收到了“未找到”消息,但不确定是什么问题
  • 如果您的数据是数字,您可能需要将您的搜索值转换为(例如)一个 Long,因为默认情况下它将是一个字符串。
  • ...如果这不起作用,那么可能会发布一些 ColA 中的示例
猜你喜欢
  • 2021-06-25
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
相关资源
最近更新 更多