感谢您提前提供任何帮助,
我有一个Access数据库,其中包含以下代码。它被设置为打开一个定义的excel文件,找到最后一行并在下面的下一行中添加1到该行的值,保存等...这是第一次执行此操作,如果再次运行它我会得到&# 34;错误' 91&#39 ;:对象变量或With块变量未设置"。但是,如果我按下VBA窗口中的停止按钮(重置)或错误消息上的结束按钮,则再次运行它可以正常工作。我尝试了很多东西而且我不知所措。
有什么建议吗?
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
亲切的问候,
答案 0 :(得分:0)
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