Q: How do I get the last used column in a specific row from an Excel sheet.
While this is a simple task using Excel VBA its more difficult using Powerpoint VBA.
Here is an example of my Excel sheet
Steps to reproduce
Sub findlastcolumn()
Set objExcel = CreateObject("Excel.application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\<USERNAME>\Desktop\data.xls")
objExcel.Visible = True
'works in Powerpoint VBA but delivers the wrong column
lastcol = objWorkbook.Sheets(1).UsedRange.Columns.Count
'produces an error in Powerpoint VBA
'but works in Excel VBA, correct column in Excel VBA
lastcol = objWorkbook.Sheets(1).Cells(1, 254).End(Direction:=xlToLeft).Column
'produces an error in Powerpoint VBA
'but works in Excel VBA, and wrong column in Excel VBA too
lastcol = objWorkbook.Sheets(1).Cells.SpecialCells(xlLastCell).Column
'wrong column. Powerpoint VBA' find method differs from Excel' find method
'searchdirection isn't available in Powerpoint VBA
lastcol = objWorkbook.Sheets(1).Rows(1).Find(what:="*", _
after:=objWorkbook.Sheets(1).Cells(1, 1), searchdirection:=xlPrevious).Column
objExcel.Quit
Set objWorkbook = Nothing
Set objExcel = Nothing
End Sub
Desired result: I want to get lastcol = 3
The comments in my code show you what I have tried so far and what error they produce.
I'm thankful for any advice.
There is no PowerPoint 2003 tag? O.o
The Excel specific code you posted should actually work and give you the same result as if you execute it in Excel.
The reason you do get error message is most likely that you did not in include the Excel reference in your Powerpoint VBA! You do use Late Binding, so it's generally not necessary to reference this library. However, the VBA compiler does not know the internal values of the Excel constants/enums xlToLeft
, xlLastCell
and xlPrevious
and therefore produces the error!
Two options to solve your issue:
? xlToLeft
- and you'll get the result (in this example -4159
). Then replace the name in your Powerpoint VBA with the number and it should work. (For better code readability, I usually leave the name of the constant in a comment in the same line, e.g. lastcol = objWorkbook.Sheets(1).Cells.SpecialCells(11).Column 'xlLastCell = 11