运行时错误91对象变量或未设置变量

问题描述 投票:1回答:3

当代码到达'在数据库中找到第一个空行时,它突出显示黄色的下两行并显示运行时错误91.任何人都可以告诉我哪里出错了。谢谢。

Private Sub diaryenter_Click()
    Dim iRow As Long
    Dim ws As Worksheet
    Set ws = Worksheets("sheet1")
    'find first empty row in database
    iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
        SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
    'copy the data to the database
    With ws
      .Cells(iRow, 115).Value = Me.autodatet.Value
      .Cells(iRow, 116).Value = Me.fdcomments.Value
      .Cells(iRow, 121).Value = Me.fdgs.Value
    End With
    'clear the data
    Me.autodatet.Value = ""
    Me.fdcomments.Value = ""
    Me.fdgs.Value = ""
    Diaryentryf.Hide
    ThisWorkbook.Save
End Sub
excel vba excel-vba runtime-error
3个回答
2
投票

它是xlByRows而不是xlRows

iRow = ws.Cells.Find(What:="*", SearchOrder:=xlByRows, _
                     SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

1
投票

也许添加一个测试,确实存在要停止的数据。如果没有找到任何内容,则会出错。

  If Application.WorksheetFunction.Counta(ws.UsedRange) = 0 Then
        iRow = 1
   Else
        iRow = ws.Cells.Find(What:="*", SearchOrder:=xlByRows, _
                             SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
   End If

感谢@Jeeped为xlByRows。


0
投票

继续@QHarr评论你应该检查FIND是否发现任何东西 (如果没有,它不能返回它没有找到的单元格的行号)。

Sub Test1()

    Dim rLastCell As Range
    Dim iRow As Long
    Dim ws As Worksheet

    Set ws = Worksheets("sheet1")

    Set rLastCell = ws.Cells.Find(What:="*", SearchOrder:=xlByRows, _
        SearchDirection:=xlPrevious, LookIn:=xlValues)
    If rLastCell Is Nothing Then
        iRow = 1
    Else
        iRow = rLastCell.Row+1
    End If

End Sub  

编辑 - 将删除,因为QHarr给出了类似的答案,但找到它是否一无所知的方法是不同的。

© www.soinside.com 2019 - 2024. All rights reserved.