Copy Excel chart to PowerPoint with embedded data using VBA - excel

After pasting a chart in from Excel, there's a "Smart Tag" that pops up in the bottom right of the chart, from which one can select "Excel chart (entire workbook)" (as opposed to the default "Chart (linked to Excel data)"). This has the effect of embedding the data in the chart so that the data can still be modified, but the chart is not linked to the Excel file. Has anyone been able to replicate this using VBA (using either in Excel-VBA or PowerPoint-VBA)?
I haven't found any way to programmatically access the "Smart Tag" from VBA. Moreover, the Paste Special options do not seem to have an option for this.
I'm using Office 2007.

Try this Tahlor:
Option Explicit
' ===========================================================================================
' Copy Specified chart to PowerPoint whilst maintaining a data link.
' Written by : Jamie Garroch of YOUpresent Ltd. (UK)
' Date : 08 JULY 2015
' For more amazing PowerPoint stuff visit us at from http://youpresent.co.uk/
' ===========================================================================================
' Copyright (c) 2015 YOUpresent Ltd.
' Source code is provide under Creative Commons Attribution License
' This means you must give credit for our original creation in the following form:
' "Includes code created by YOUpresent Ltd. (YOUpresent.co.uk)"
' Commons Deed # http://creativecommons.org/licenses/by/3.0/
' License Legal # http://creativecommons.org/licenses/by/3.0/legalcode
' ===========================================================================================
' Macro Execution Environment : Designed to run in Excel VBA.
' ===========================================================================================
' You can use Early Binding (with the advantage that IntelliSense adds) by adding a reference
' to the PowerPoint Object Library and setting the compiler constant EARLYBINDING to True
' but delete it afterwards otherwise you will face a nightmare of compatibility!!!
' ===========================================================================================
#Const EARLYBINDING = False
Sub CopyPasteLinkedChartToPowerPoint()
#If EARLYBINDING Then
' Define Early Binding PowerPoint objects so you can use IntelliSense while debuggging
' Requires a reference (Tools/References) to the Microsoft PowerPoint XX.Y Object Library
Dim oPPT As PowerPoint.Application
Dim oPres As PowerPoint.Presentation
Dim oSld As PowerPoint.Slide
#Else
' Define Late Binding PowerPoint objects
' Remove the reference to the Microsoft PowerPoint Object Library
Dim oPPT As Object
Dim oPres As Object
Dim oSld As Object
Const ppLayoutTitle = 1
#End If
' Define Excel objects
Dim oWB As Workbook
Dim oWS As Worksheet
Dim oCHT As ChartObject
Set oPPT = CreateObject("PowerPoint.Application")
Set oPres = oPPT.Presentations.Add(msoTrue)
Set oSld = oPres.Slides.Add(1, ppLayoutTitle)
' Modify these lines according to how you want to selet the chart
Set oWB = ActiveWorkbook
Set oWS = oWB.Worksheets(1)
Set oCHT = oWS.ChartObjects(1)
oCHT.Select
ActiveChart.ChartArea.Copy
' Paste the chart to the PowerPoint slide with a data link
oSld.Shapes.PasteSpecial link:=msoTrue
' Clear objects
Set oPPT = Nothing: Set oPres = Nothing: Set oSld = Nothing
Set oWB = Nothing: Set oWS = Nothing: Set oCHT = Nothing
End Sub

This is probably really bad form (posting as an answer to my question the answer to Joel's question in his answer), but the code below should help you with your question Joel. This is designed to be run from PowerPoint, and will delete all of the sheets that the selected chart doesn't use. Porting this to Excel should be pretty straightforward, just make sure chart1 is the PowerPoint chart you just pasted in and not the Excel chart you copied over. In any event, be extra careful to make sure that the graphs are being pasted in with the data (as opposed to being linked to the original workbook), as this code will delete every extra sheet in whatever workbook the chart references.
This has not been tested thoroughly. Obviously, back everything up.
'Delete extra sheets of selected chart in PowerPoint
Sub delete_excess_sheets()
Application.DisplayAlerts = False
Dim chart1 As Chart, used_sheets As Collection
Set chart1 = ActiveWindow.Selection.ShapeRange(1).Chart
chart1.ChartData.Activate
chart1.ChartData.Workbook.Application.DisplayAlerts = False
'Get sheets being used by chart
Set used_sheets = find_source(chart1)
For Each sht In chart1.ChartData.Workbook.worksheets 'this only loops through worksheets, not worksheet-charts
'note that you might first copy/paste values of the sheet supporting the data, if that sheet itself refers to other sheets
If Not InCollection(used_sheets, sht.Name) Then
sht.Delete
End If
Next
Application.DisplayAlerts = True
chart1.ChartData.Workbook.Application.DisplayAlerts = True
End Sub
'Determine which sheets are being used by the chart
Function find_source(search_cht As Object) As Collection
Dim strTemp As String, sheet_collection As New Collection
For Each mysrs In search_cht.SeriesCollection
first_part = Split(Split(mysrs.Formula, "!")(0), "=SERIES(")(1)
If (InStr(first_part, "'") = 1 And Right(first_part, 1) = "'") Then first_part = Mid(first_part, 2, Len(first_part) - 2)
sheet_collection.Add first_part, first_part
Next
Set find_source = sheet_collection
End Function
'Determine if object is in a collection
Public Function InCollection(col As Collection, key As String) As Boolean
Dim var As Variant
Dim errNumber As Long
InCollection = False
Set var = Nothing
err.Clear
On Error Resume Next
var = col.Item(key)
errNumber = CLng(err.Number)
On Error GoTo 0
'5 is not in, 0 and 438 represent incollection
If errNumber = 5 Then ' it is 5 if not in collection
InCollection = False
Else
InCollection = True
End If
End Function

Related

User type not defined macro error vba in method

I am trying to call a sub function, but fails with an error:
User type not defined on the saveas method at this line. Maybe presentation isn't being processed in vba
The error is on the first line of SavePDFAsPng:
Dim oPres As Presentation
Here is the whole macro:
Sub Button1_Click()
Call SavePDFAsPng("C:\Users\gfas1\Desktop\ahm.pdf", "C:\Users\gfas1\Desktop\MyTest.PNG")
End Sub
Sub SavePDFAsPng(sPathToPDF As String, sPathToPNG As String)
Dim oPres As Presentation
Dim oSh As Shape
' Height/Width are hardcoded here
' You could get trickier and bring the PDF into any presentation
' once to get its proportions, delete it, set the slide size to the same
' proportions, then re-insert the PDF
Dim sngWidth As Single
Dim sngHeight As Single
sngWidth = 612
sngHeight = 792
Set oPres = Presentations.Add
With oPres
With .PageSetup ' set it to 8.5x11
.SlideHeight = sngHeight ' 11in * 72 points per inch
.SlideWidth = sngWidth
End With
.Slides.AddSlide 1, .SlideMaster.CustomLayouts(1)
With .Slides(1)
Set oSh = .Shapes.AddOLEObject(0, 0, sngWidth, sngHeight, , sPathToPDF)
Call .Export(sPathToPNG, "PNG")
End With
.Saved = True
.Close
End With
End Sub
You tagged the question with "Excel", so I assume you're trying to run this macro in Excel, which won't work because the Presentation type is not in Excel by default.
It's in PowerPoint:
https://learn.microsoft.com/en-us/office/vba/api/overview/powerpoint/object-model
https://learn.microsoft.com/en-us/office/vba/api/powerpoint.presentation
You need to run this macro in PowerPoint, not Excel.
You can run it in Excel, but you need to import the PowerPoint type-library into your Excel VBA project, but that's a separate question.

How can I copy an image from excel to a Shape of PPT?

I try this code, to copy from excel to ppt:
Dim presentation As Object
Set ppt = CreateObject("PowerPoint.Application")
Set presentation = ppt.Presentations.Open2007("D:\temp.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue)
Dim oSlide As Object
Set oSlide = presentation.Slides(7)
Dim oSheet As Worksheet
Set oSheet = ThisWorkbook.Sheets(2)
Dim oImageOb As Object
Set oImageOb = oSheet.Shapes(1)
oImageOb.Copy
oSlide.Shapes.PasteSpecial DataType:=2
But PPT exits after the execution of PasteSpecial .
How can I copy an image from excel to a Shape of PPT?
Not sure if it makes a difference, but I like to explicitly state what kind of object I refer to when using VBA from Excel to PowerPoint:
Dim presentation As PowerPoint.Presentation
Set ppt = New PowerPoint.Application
Set presentation = ppt.Presentations.Open2007("D:\temp.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue)
Dim oSlide As Object
Set oSlide = presentation.Slides(7)
Dim oSheet As Worksheet
Set oSheet = ThisWorkbook.Sheets(2)
Dim oImageOb As Object
Set oImageOb = oSheet.Shapes(1)
oImageOb.Copy
oSlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile
This code works fine for me (just replacing the location of the PPT-file, of course). And by "works", I mean the figure/image/shape is copied from excel to powerpoint, without powerpoint closing afterwards
This seems to be a timing problem. It bites some people/some PCs and not others. You paste the shape and then try to do something with it while PPT is still processing the request, so the "do something wit it" part fails.
The usual workaround is to give it a little extra time and try a few extra times:
In the Declarations section of your module, include this:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
That's for 32-bit PowerPoint; getting it to work in 64-bit PPT or in both is possible, but a subject for a different thread.
Then in the part of your sub that pastes the shape, try pasting several times with a pause between each try:
Dim oShp as Shape
Dim x as Long
On Error Resume Next
For x = 1 to 3 ' or whatever number you want to try
Set oShp = oSlide.Shapes.PasteSpecial DataType:=2
Sleep(1000) ' Adjust this as needed
If Not oShp is Nothing Then
Exit For
End If
Next
If oShp is Nothing Then
' It didn't work.
' Do whatever you need to do to recover
End If
On Error GoTo YourRegularErrorHandler
' Which you should add
In order to paste the image into the specified shape in PowerPoint, there are some caveats:
The Shape must be of a type that allows images, such as certain content placeholders. You cannot insert images into text boxes, chart placeholders, etc.
The Shape must be Selected. While we're accustomed to telling people to avoid using Select or Activate in Excel VBA, in PowerPoint and Word however, certain actions can only be performed when the object is in view and/or selected. In order to Select the shape, we need to Select the slide.
I've cleaned up your procedure by moving the variable declarations to the top, and modified the path/slide indices etc. I've created a new variable pptShape which we'll use to handle the specific shape instance on the slide.
Note that I've changed the path and slide/shape indices.
Option Explicit
Sub foo()
Dim ppt As Object 'PowerPoint.Application
Dim oSlide As Object 'PowerPoint.Slide
Dim pptShape As Object 'PowerPoint.Shape
Dim oImageOb As Object
Dim oSheet As Worksheet
Dim pres As Object 'PowerPoint.Presentation
Set ppt = CreateObject("PowerPoint.Application")
Set pres = ppt.Presentations.Open2007("c:\debug\empty ppt.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue)
Set oSlide = pres.Slides(3)
Set oSheet = ThisWorkbook.Sheets(1) ' ## MODIFY AS NEEDED
Set oImageOb = oSheet.Shapes(1) ' ## MODIFY AS NEEDED
oImageOb.Copy
Set pptShape = oSlide.Shapes(1) ' ## MODIFY AS NEEDED
'## to preserve aspect ratio and prevent stretching/skewing image:
pptShape.Width = oImageOb.Width
pptShape.Height = oImageOb.Height
' ## Select the slide
oSlide.Select
' ## Selct the shape
' ## NOTE: This shape MUST be of a type that contains a picture frame, otherwise
' an error will occur
pptShape.Select
' ## All of the following methods work for me:
'ppt.CommandBars.ExecuteMso "PasteJpeg"
'ppt.CommandBars.ExecuteMso "PasteBitmap"
'ppt.CommandBars.ExecuteMso "PasteAsPicture"
ppt.CommandBars.ExecuteMso "Paste"
End Sub
Here is my Excel sheet with an image:
And the output, slide with the image pasted into the appropriate Image Placeholder:

Paste method of Chart object not working as expected in Excel 2016

I have a code, recently updated to Excel 2016 that has shown some strange malfunctions. After quite a lot of debugging, I found that one of the errors were caused by Excel failing to handle a image correctly.
The code below has a simple purpose, to copy a used part of a worksheet to an image, and then insert that image as a comment in a worksheet.
However, in order for the function to work properly in Excel 2016, I need to repeat the paste operation several times as you can see in the code.
The workaround is functional, but I believe that some degree of understanding of why is needed, and I would also prefer a more clean solution.
Public Sub CopySheetToComment(ReferenceSheet As Worksheet, Target As Range)
Dim rng As Range
Dim Sh As Shape
Dim pWidth As Single
Dim PHeight As Single
Dim cmt As Comment
Dim TempPicFile As String
Application.ScreenUpdating = True
' Path temporary file
TempPicFile = Environ("temp") & "\img.png"
' Define and copy relevant area
Set rng = ReferenceSheet.UsedRange
rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
pWidth = rng.Width
PHeight = rng.Height
' Paste copied image to chart and then export to file
Dim C As Object
Set C = ReferenceSheet.Parent.Charts.add
Dim Ch As ChartObject
Set Ch = C.ChartObjects.add(Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)
' Ugly solution that is working in Excel 2016....
Ch.Chart.Paste
DoEvents
Ch.Chart.Paste
DoEvents
Ch.Chart.Paste
Ch.Chart.Export TempPicFile
' Remove chart object
Dim Alerts As Boolean
Alerts = Application.DisplayAlerts
Application.DisplayAlerts = False
C.Delete
Application.DisplayAlerts = Alerts
' Remove old comment
On Error Resume Next
Target.Comment.Delete
On Error GoTo 0
Application.ScreenUpdating = True
' Add comment
Set cmt = Target.AddComment
Target.Comment.Visible = True
' Infoga bild till kommentar
With cmt.Shape
.Fill.UserPicture TempPicFile
.Width = pWidth * 1.33333
.Height = PHeight * 1.33333
End With
'Target.Comment.visible = False
End Sub
And to call it, this example works:
Sub test()
Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("blad2")
CopySheetToComment ws, Range("D8")
End Sub
Theories on why this works but not DoEvents, or suggestions for proper code is requested.
Ran into similar problems after updating my Excel version. This is how I solved it:
Dim pChart As Chart 'will serve as a temporary container for your pic
rng.CopyPicture xlScreen, xlPicture 'using the rng you use in your code here
Set pChrt = Charts.Add
ActiveChart.ChartArea.Clear
With pChrt
.ChartArea.Parent.Select 'new for Excel 2016
.Paste
.Export Filename:=TempPicFile, Filtername:="PNG" 'TempPicFile is what you defined in your code, so path + file name
.Delete
End With
You can then use the PNG and paste it as you do, asigning a width/height to it.
Additionally, I would set Application.DisplayAlerts = Falseat the beginning of a sub and set it back to Truejust at the end - quicker and less hassle.
Also works with:
Dim Ch As ChartObject
'adding
Ch.Chart.Parent.Select
'then
Ch.Chart.Paste
'because Microsoft....

How to dynamically reference PowerPoint slides using VBA

I've written/compiled a macro that opens an Excel file, creates a PowerPoint chart and populates the chart worksheet with data from a worksheet in the Excel file.
I'm trying to alter the macro to loop through the Excel file's worksheets and:
for each worksheet create a PowerPoint slide and chart
populate the PowerPoint chart with data from the worksheet in the Excel file
Presently when I run the macro, the first PowerPoint chart and slide is created correctly. The second slide is created for the Excel file's second worksheet but the PowerPoint chart is not created correctly. The workbook that I'm testing the macro on has two worksheets.
What is the correct way to dynamically reference each new PowerPoint slide? As of now I've been using:
Set pptWorkSheet = pptWorkBook.Worksheets(ActivePresentation.Slides.Count) 'sorta works-changed 8/19
When I go to the debugger it says ActivePresentation.Slides.Count = 2 so I am not sure as to why its not transferring the data to the second PowerPoint chart.
I also may not be referring to the Excel file worksheets correctly here:
pptWorkSheet.Range("a2:b5").Value = xlWB.ActiveSheet.Range("a2:b5").Value
Below is the full macro:
Sub CreateChartAllWKs()
'Create variables
Dim myChart As Chart
Dim pptChartData As ChartData
Dim pptWorkBook As Excel.Workbook
Dim pptWorkSheet As Excel.Worksheet
Dim xlApp As Excel.Application
Dim xlWB As Workbook
Dim xlWS As Worksheet
' Create new excel instance and open relevant workbook
Set xlApp = New Excel.Application
xlApp.Visible = True 'Make Excel visable
Set xlWB = xlApp.Workbooks.Open("C:\filepath\ExcelData.xlsm", True, False) 'Open relevant workbook
'Loop through each worksheet in xlWB and transfer data to new pptWorkBook and
'create new PowerPoint chart
For Each xlWS In ActiveWorkbook.Worksheets
'Add a new slide where we will create the PowerPoint worksheet and chart
ActivePresentation.Slides.Add ActivePresentation.Slides.Count + 1, ppLayoutText
ActiveWindow.View.GotoSlide ActivePresentation.Slides.Count
Set activeSlide = ActivePresentation.Slides(ActivePresentation.Slides.Count)
' Create the chart and set a reference to the chart data.
Set myChart = activeSlide.Shapes.AddChart.Chart 'changed 8/19
Set pptChartData = myChart.ChartData
' Set the PowerPoint Workbook and Worksheet references.
Set pptWorkBook = pptChartData.Workbook
Set pptWorkSheet = pptWorkBook.Worksheets(ActivePresentation.Slides.Count) 'sorta works-changed 8/19
' Add the data to the PowerPoint workbook.
pptWorkSheet.ListObjects("Table1").Resize pptWorkSheet.Range("A1:B5")
pptWorkSheet.Range("Table1[[#Headers],[Series 1]]").Value = "Items"
pptWorkSheet.Range("a2:b5").Value = xlWB.ActiveSheet.Range("a2:b5").Value 'transfer data from ExcelWB to pptWorkSheet (i.e. the PowerPoint workbook)
' Apply styles to the chart.
With myChart
.ChartStyle = 4
.ApplyLayout 4
.ClearToMatchStyle
End With
' Add the axis title.
With myChart.Axes(xlValue)
.HasTitle = True
.AxisTitle.Text = "Units"
End With
'Apply data labels
myChart.ApplyDataLabels
Next xlWS
' Clean up the references.
Set pptWorkSheet = Nothing
' pptWorkBook.Application.Quit
Set pptWorkBook = Nothing
Set pptChartData = Nothing
Set myChart = Nothing
'Clean up Excel references.
Set xlApp = Nothing
'Option to close excel workbook
'ExcelWB.Close
End Sub
I think the problem you are running into is how PowerPoint and Excel store slide numbers and worksheet numbers. PowerPoint at least 3 different attributes with Slides, including "Slide IDs", "Slide Indexes" and "Slide Numbers". They are all different and make things a pain when you are trying to reference them. What I like to do is actually set the reference of the slide right when I am creating the slide:
Set CurSlide = ActivePresentation.Slides.Add(ActivePresentation.Slides.Count + 1, ppLayoutText)
This way right when you create the slide you now have a reference to it.
Additionally I find that using a number as a worksheet reference can also cause issues since if you reference the 5th worksheet it may not be the 5th worksheet at all. You have to look in the VBA editor of Excel to see what sheet gets what reference. However if you are able to refer to the worksheet name such as "Sheet1", "Sheet2", "OtherWorksheet" etc. You can make things a lot easier. To put this a little more in perspective if you make a sheet named "5" and then call the worksheet with.
Set ws = ActiveWorkBook.WorkSheets(5)
It will not work. You would need to use
Set ws = ActiveWorkBook.Worksheets("5")
Hopefully that makes sense. This part is not necessary but it makes debugging a lot easier if you do run into issues. The way I would recommend to do this is not in my code below because I don't have your workbook.
Set PPtWorkSheet = pptWorkBook.Worksheets("Sheet" & CurSlide.SlideIndex)
I re-wrote a few lines of your code and I was able to get it to work. However I do not have a copy of your workbook so I am not 100% sure this would work. Consider changing the worksheet names on your workbook if you still have trouble referencing the worksheet from the slide Index.
The revised code is below let me know if you have any questions.
Sub CreateChartAllWKs()
'Create variables
Dim myChart As Chart
Dim pptChartData As ChartData
Dim pptWorkBook As Excel.Workbook
Dim pptWorkSheet As Excel.Worksheet
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim CurSlide As Slide 'new from update
' Create new excel instance and open relevant workbook
Set xlApp = New Excel.Application
xlApp.Visible = True 'Make Excel visable
Set xlWB = xlApp.Workbooks.Open("C:\filepath\ExcelData.xlsm", True, False) 'Open relevant workbook
'Loop through each worksheet in xlWB and transfer data to new pptWorkBook and
'create new PowerPoint chart
For Each xlWS In ActiveWorkbook.Worksheets
'Add a new slide where we will create the PowerPoint worksheet and chart
'Set CurSlide = ActivePresentation.Slides.Add ActivePresentation.Slides.Count + 1, ppLayoutText
ActiveWindow.View.GotoSlide ActivePresentation.Slides.Count
'This is my recommendation
Set CurSlide = ActivePresentation.Slides.Add(ActivePresentation.Slides.Count + 1, ppLayoutText)
' Create the chart and set a reference to the chart data.
Set myChart = CurSlide.Shapes.AddChart.Chart 'changed 8/19
Set pptChartData = myChart.ChartData
' Set the PowerPoint Workbook and Worksheet references.
Set pptWorkBook = pptChartData.Workbook
Set pptWorkSheet = pptWorkBook.Worksheets(CurSlide.SlideIndex) 'From Update
' Add the data to the PowerPoint workbook.
pptWorkSheet.ListObjects("Table1").Resize pptWorkSheet.Range("A1:B5")
pptWorkSheet.Range("Table1[[#Headers],[Series 1]]").Value = "Items"
pptWorkSheet.Range("a2:b5").Value = xlWB.ActiveSheet.Range("a2:b5").Value 'transfer data from ExcelWB to pptWorkSheet (i.e. the PowerPoint workbook)
' Apply styles to the chart.
With myChart
.ChartStyle = 4
.ApplyLayout 4
.ClearToMatchStyle
End With
' Add the axis title.
With myChart.Axes(xlValue)
.HasTitle = True
.AxisTitle.Text = "Units"
End With
'Apply data labels
myChart.ApplyDataLabels
Next xlWS
' Clean up the references.
Set pptWorkSheet = Nothing
' pptWorkBook.Application.Quit
Set pptWorkBook = Nothing
Set pptChartData = Nothing
Set myChart = Nothing
'Clean up Excel references.
Set xlApp = Nothing
'Option to close excel workbook
'ExcelWB.Close
End Sub

Read Excel file sheet names

I have an export process that transfers data from my Access tables to an Excel File. A couple times I have had issues where the process didn't generate one or more of the sheets (1 sheet = 1 table) in Excel. So when the transfers are complete I want Access to check if all the sheets are located in the Excel file. I have most of the Check process worked out all I need now is a way to "read" the sheet names from the Excel File in to a table. How can I read the Sheet name (not the data)?
From Access you can automate Excel, open the workbook file, and read the sheet names from the Worksheets collection.
This sample uses late binding. If you prefer early binding, add a reference for Microsoft Excel [version] Object Library and enable the "early" lines instead of the "late" lines.
Give the procedure the full path to your workbook file as its pWorkBook parameter.
Public Sub List_worksheets(ByVal pWorkBook As String)
'Dim objExc As Excel.Application ' early
'Dim objWbk As Excel.Workbook ' early
'Dim objWsh As Excel.Worksheet ' early
Dim objExc As Object ' late
Dim objWbk As Object ' late
Dim objWsh As Object ' late
'Set objExc = New Excel.Application ' early
Set objExc = CreateObject("Excel.Application") ' late
Set objWbk = objExc.Workbooks.Open(pWorkBook)
For Each objWsh In objWbk.Worksheets
Debug.Print objWsh.Name
Next
Set objWsh = Nothing
objWbk.Close
Set objWbk = Nothing
objExc.Quit
Set objExc = Nothing
End Sub
In Access 2007, You can use OpenDatabase method to do this:
Private Sub Command1_Click()
Set db = OpenDatabase("c:/123.xls", True, False, "Excel 5.0")
For Each tbl In db.TableDefs
MsgBox tbl.Name
Next
End Sub

Resources