且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Access VBA 如何将新工作表添加到 Excel?

更新时间:2023-11-30 22:41:52

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