2009-08-03 67 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