为什么我的代码出现运行时错误91?

时间:2020-07-21 15:42:28

标签: excel vba variables runtime-error

当我尝试运行此代码时,出现错误“运行时错误'91':对象变量或未设置块变量”我是VBA的新手,所以我不太了解问题所在。我相信这与“以字符串形式显示当前行”有关,因为我知道我必须声明该变量,但是我似乎无法弄清楚问题是什么。你有什么想法?预先感谢。

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

1 个答案:

答案 0 :(得分:2)

无论何时执行查找:

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

赞:

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