access sub 运行一次然后错误'91':未设置对象变量

access sub runs once then Error '91': object variable not set

提前感谢您的帮助,

我有一个包含以下代码的 Access 数据库。它被设置为打开一个定义的 excel 文件,找到最后一行并将该行的值加 1 到下一行中的值,保存等......它第一次这样做,如果你 运行 我又得到了 "Error '91': Object variable or With block variable not set"。但是,如果我在 VBA window 中按下停止按钮(重置)或错误消息上的结束按钮,则 运行 它再次起作用。我已经尝试了很多东西,但我很茫然。

有什么建议吗?

Private Sub quoteNew1_Click()

    Dim app As New Excel.Application
    app.Visible = True

    Dim book As Excel.Workbook
    Set book = app.Workbooks.Add("C:\Desktop\Test_Quotes.xlsx") 

    nextEmptyRow  'find last row and add new value to next row colum a

    book.Close savechanges:=True

    app.Quit
    Set app = Nothing

End Sub


Sub nextEmptyRow()
    Dim emptyRow As Long

    emptyRow = ActiveSheet.UsedRange.Rows.Count

    MsgBox emptyRow

    Cells(emptyRow + 1, 1).Value = Cells(emptyRow, 1).Value + 1

End Sub

亲切的问候,

Workbooks.Add 想要一个模板作为参数。第一次添加新工作簿时,您将希望使用以下格式。之后,您需要打开现有的工作簿。以下代码对我有用,似乎可以满足您每次使用增量值添加新行的要求。

Private Sub quoteNew1_Click()

Dim app As New Excel.Application
app.Visible = True

Dim book As Excel.Workbook

'If workbook exists open it, otherwise create it
If Len(Dir("C:\temparea\Test_Quotes.xlsx")) = 0 Then
    'File doesn't exist, create it
    Set book = Workbooks.Add
    app.DisplayAlerts = False
    book.SaveAs FileName:="C:\temparea\Test_Quotes.xlsx"
    app.DisplayAlerts = False
Else
    'Open existing file
    Set book = Workbooks.Open("C:\temparea\Test_Quotes.xlsx")
End If

nextEmptyRow  'find last row and add new value to next row colum a

book.Close savechanges:=True

app.Quit
Set app = Nothing
End Sub

Sub nextEmptyRow()
Dim emptyRow As Long

emptyRow = ActiveSheet.UsedRange.Rows.Count

If Cells(emptyRow, 1).Value = 0 Then
    ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value + 1
Else
    Cells(emptyRow + 1, 1).Value = Cells(emptyRow, 1).Value + 1
End If

End Sub