2009-08-03 61 views
1

我正在运行几个访问代码模块,并且正在将数据写入 Excel。当我第一次写入时,数据被正确写入。但是当我尝试时,又一次 ,新数据写在旧数据的顶部。我应该怎么做 插入一张新表?访问VBA如何添加新工作表到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 
+0

是的,这是如果工作表1填充,然后转到工作表2,如果工作表2填充,然后去工作表3等等。 – tksy 2009-08-05 10:27:23

回答

3

我认为下面的代码应该做你想要什么。它和你的非常相似,只不过它使用.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 
+0

这仍然会执行相同的功能。当我repaetedly运行的代码数据将bve复制到sheet1只 – tksy 2009-08-03 11:44:40