Access VBA 如何将新工作表添加到 Excel? [英] Access VBA How to add new sheets to excel?

查看:33
本文介绍了Access VBA 如何将新工作表添加到 Excel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am running a few modules of code in access and am writing data into Excel. When I write the first time, data gets written properly. But again when I try, the new data is written on top of the old data. What should I do to insert a new sheet?

My existing code is

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

解决方案

I think that the following code should do what you want. It's very similar to yours, except it uses the return values from the .Add methods to get the objects you want.

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

这篇关于Access VBA 如何将新工作表添加到 Excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆