访问VBA如何将新表添加到Excel中?

我正在运行几个访问代码模块,并将数据写入Excel。 当我第一次写,数据得到正确写入。 但是再次尝试时,新数据写在旧数据的顶部。 我应该怎么做才能插入新的表单?

我现有的代码是

Dim objexcel As Excel.Application Dim wbexcel As Excel.Workbook Dim wbExists As Boolean Dim objSht As Excel.Worksheet Dim objRange As Excel.Range Set objexcel = CreateObject("excel.Application") On Error GoTo Openwb wbExists = False Set wbexcel = objexcel.Workbooks.Open("C:\REPORT1.xls") Set objSht = wbexcel.Worksheets("Sheet1") objSht.Activate wbExists = True Openwb: On Error GoTo 0 If Not wbExists Then objexcel.Workbooks.Add Set wbexcel = objexcel.ActiveWorkbook Set objSht = wbexcel.Worksheets("Sheet1") End If 

我认为下面的代码应该做你想做的。 它和你的非常相似,除了它使用.Add方法的返回值来获取你想要的对象。

 Public Sub YourSub() Dim objexcel As Excel.Application Dim wbexcel As Excel.Workbook Dim wbExists As Boolean Set objexcel = CreateObject("excel.Application") 'This is a bad way of handling errors. We should' 'instead check for the file existing, having correct' 'permissions, and so on, and actually stop the process' 'if an unexpected error occurs.' On Error GoTo Openwb wbExists = False Set wbexcel = objexcel.Workbooks.Open("C:\REPORT1.xls") wbExists = True Openwb: On Error GoTo 0 If Not wbExists Then Set wbexcel = objexcel.Workbooks.Add() End If CopyToWorkbook wbexcel EndSub Private Sub CopyToWorkbook(objWorkbook As Excel.Workbook) Dim newWorksheet As Excel.Worksheet set newWorksheet = objWorkbook.Worksheets.Add() 'Copy stuff to the worksheet here' End Sub