【问题标题】:Runtime error 91 object variable or with variable not set运行时错误 91 对象变量或未设置变量
【发布时间】:2018-05-15 18:47:06
【问题描述】:

当代码到达“在数据库中查找第一个空行”时,它会以黄色突出显示接下来的两行并显示运行时错误 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

【问题讨论】:

  • 哪一行出现错误?
  • xlByRows 不是xlRows
  • Worksheets("sheet1") 中有数据吗?否则会报错
  • 嗯,看起来有点眼熟...(它仍然不是数据库);-)

标签: vba excel runtime-error


【解决方案1】:

这是xlByRows 而不是xlRows

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

【讨论】:

  • 这就是为什么应该使用Option Explicit
  • 它似乎与 xlRows 一起工作这会影响实际机制吗?
  • 我刚刚在“即时”窗口中仔细检查了一遍。实际上,xlByRows 和 xlRows 都返回 1,所以它们实际上是可以互换的。
【解决方案2】:

可能会添加一个测试,证明确实有数据要停止。如果没有可查找的内容,请查找错误。

  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。

【讨论】:

    【解决方案3】:

    从@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 给出了类似的答案,但查找它是否没有的方法不同。

    【讨论】:

      猜你喜欢
      • 2016-10-07
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多