Error in addressing an open Excel file, using VBA in PowerPoint - excel

I am trying to have a vba macro in PowerPoint to open and retrieve information from an Excel file.
The Excel file is saved in a SharedPoint and I am able to open it. However, when I want to refer to the Workbook as to retrieve information from it's cells, it gives me the following error: Automation error invalid syntax -2147221020 (800401e4)
Here is the code I have so far:
Sub test()
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Application.DisplayAlerts = False
'open excel from sharedpoint
ActivePresentation.FollowHyperlink _
Address:="http://teams.blabla.com/Shared%20Documents/Overview_NPD_Projects.xlsm", _
NewWindow:=True, AddHistory:=True
Set wb = GetObject("http://teams.blabla.com/Shared Documents/Overview_NPD_Projects.xlsm")
' this does not work even when I change it to "Shared%20Documents"
Set ws = wb.Worksheets("Project List")
auxvariable = ws.Range("B2").Value
End Sub
The funny thing is that it works if I try to save the excel file manually to my desktop before running the macro and change the the path to:
Set wb = GetObject("C:\Users\Filipe.freitas\Desktop\Overview_NPD_Projects.xlsm")
I would save the file to the desktop and use the correct path, but I would need to refer to the excel file before doing it.
Any help would be greatly appreciated!

Have you tried http://www.cpearson.com/Excel/DownloadFile.aspx and then
Dim xlapp as object
xlapp = createobject("Excel.Application")
set wb = xlapp.workbooks.open("thefilenamewhereyousavethedownload")

Related

How to open an Excel workbook from Access

I currently have a string in Microsoft Access that is delegating functions to an external Application.
I have gotten so far as to copying a set of data from the external application.
I want to paste this into an excel workbook that is not open but exists. C:\Users\abcdef\Desktop KDNR.xlsx
how can I integrate this function into my sub procedure?
Thank you in advance
I attempted simply writing
Dim x as Workbook
set x = Workbooks.Open (" workbook name ")
Howoever, i got the compile error "user defined type not defined"
when i just write
Workbooks.Open (" workbook name ")
i get the compile error
"variable not defined"
Use Excel From Access
This is a basic example of how to work with Excel from Access.
It opens a new instance of Excel (whether Excel is open or not), opens the workbook, writes the string Test to cell A1 of worksheet Sheet1, saves and closes the workbook, and finally quits the Excel instance.
' If you haven't already, create a reference to
' "Tools->References->Microsoft Excel 16.0 Object Library"!
Sub Test()
Dim DestinationFilePath As String
DestinationFilePath = Environ("USERPROFILE") & "\DeskTop\KDNR.xlsx"
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
xlApp.Visible = True ' out-comment when done developing; default is 'False'
Dim wb As Workbook: Set wb = xlApp.Workbooks.Open(DestinationFilePath)
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
ws.Range("A1").Value = "Test"
wb.Close SaveChanges:=True
xlApp.Quit
End Sub

Activating opened Excel workbook from Outlook

I have a macro in my Outlook that whenever I receive an e-mail with a certain subject, it automatically opens an Excel workbook and pastes a portion of the e-mail subject in a specific cell in one of the worksheets. It works perfectly. Now I need to do this exact same process but pasting this information in an already opened workbook, instead of opening a closed file.
I've tried different solutions from my limited Excel VBA knowledge (ActiveWorkbook, worbooks(filename).activate, etc.) but none of that worked and I have not found anything similar online, as most macros are written as being run from an Excel file and not Outlook.
This is part of our current code, that opens the file and pastes the e-mail subject (which is the "ticker" value) in a specific cell on the "Lista Empresas" worksheet. What I need is a code that does the same, but in an workbook that is already opened (let's call it "test1").
Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate
There are a few scenarios to handle here. First, is Excel running? If no, then do what you are doing already. If yes - is the correct workbook open? If yes - return it, otherwise open it.
Dim ExWbk2 As Workbook
Dim wb As Workbook
Dim exapp As Excel.Application
On Error Resume Next
Set exapp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set exapp = Nothing
End If
On Error GoTo 0
If exapp Is Nothing Then
' Excel is not running
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
ExWbk2.Visible = True
Else
' Excel is running, but is the right book open?
For Each wb In exapp.Workbooks
Debug.Print wb.Name ' <-- This will help you find what to look for
If wb.Name = "ListaEmpresas_ajustado" Then
' Yes, it is!
Set ExWbk2 = wb
End If
Next
If ExWbk2 Is Nothing Then
' No, it wasn't
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
End If
End If
The trick to find out if Excel is running is GetObject. It will fail if it can't find it.
The for loop is there to allow for finding the correct workbook, based on the name. Adjust as needed.
The following code gets the object if you know the name of the sheet currently active in Excel instance. I guess this could be got from the application title using the first bit of code.
Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = GetObject("ListaEmpresas_ajustado.xlsm").Application
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate

Embedding PDF in Spreadsheet

Goal is to run this subroutine in an Access application, which embeds a PDF document in a new Excel workbook. The sub works properly with a text file, but will give error "Run-time error '1004': Document not saved." with a PDF file. The code breaks on the SaveAs method. Why does one file-type embed, and the PDF file-type not work? Any help will be appreciated.
Sub SavePDFInWorkBook()
Dim xlObj As New Excel.Application ' Excel application
Dim wbkObj As Excel.workbook ' workbook object
Dim wstObj As Excel.Worksheet ' worksheet object
Dim oleObj As Excel.OLEObject ' embeded object
Dim EmbedFile, MyWbk As String
MyWbk = "M:\SS\DD\Projects\cash_dep2000\TEST.xlsx"
EmbedFile = "M:\SS\DD\Projects\cash_dep2000\DaytonFreight.pdf"
Set wbkObj = xlObj.Workbooks.Add ' workbook is added in open condition in memory
Set wstObj = wbkObj.Worksheets(1) ' workbook is created with one worksheet
Set oleObj = wstObj.OLEObjects.Add(, EmbedFile, False, True)
wbkObj.SaveAs (MyWbk) ' saves workbook to folder
wbkObj.Close ' closes workbook in folder
Set oleObj = Nothing
Set wstObj = Nothing
Set wbkObj = Nothing
Set xlObj = Nothing
MsgBox ("Test Complete")
End Sub
This works to embed pdf icon/link but it also opens the pdf. Aggravating.
ActiveSheet.OLEObjects.Add(Filename:="C:\Users\June\MyStuff\DMV.pdf", Link:=False, _
DisplayAsIcon:=True, IconFileName:= _
"C:\WINDOWS\Installer\{AC76BA86-7AD7-1033-7B44-AB0000000001}\PDFFile_8.ico", _
IconIndex:=0, IconLabel:="whatever you want").Activate
I can manually save the file but SaveAs code for macro-enabled workbook errors. More aggravating. Maybe modifying to your object manipulation code will work.

How to get reference to an open Excel spreadsheet from Word?

I have some VBA code that copies stuff from Excel and pastes it into Word. The problem I'm having is how to open the spreadsheet. I can open it using an absolute path reference by
Workbooks.Open "C:\path\filename.xls"
I would prefer to reference the spreadsheet using a relative path reference. I was able to find code for relative path references from an Excel workbook to another one but it doesn't seem to work if you're doing it from Word.
Add a reference to Excel object library, then create an object in code and use that object to control an instance of Excel. Just make sure to avoid things like ActiveWorkbook, just in case.
After adding the reference:
Sub DoStuffWithExcelInWord()
Dim xl As Excel.Application
Dim wkbk As Excel.Workbook
Dim wk As Excel.Worksheet
Set xl = CreateObject("Excel.Application")
Set wkbk = xl.Workbooks.Open("C:\test.csv")
Set wk = wkbk.Sheets(1)
Debug.Print wk.Cells(1, 1).Value
xl.Quit
Set wk = Nothing
Set wkbk = Nothing
Set xl = Nothing
End Sub
You can create something very similar using Excel to automate Word too, if that's more of what you're looking for.

Run excel macro on multiple files

I have an excel macro saved in a blank workbook and multiple data workbooks.
I currently open the macro file and each data file individually, running the macro on each one with a keyboard shortcut.
Is there a way to run the macro on all the data workbooks without opening them, either with
a batch file,
VBA/VBScript,
powershell,
or something similar?
One way to do this is to add your macro's to the file PERSONAL.XLSB. This file will be loaded in the background every time you start Excel. Initially the PERSONAL.XLSB file will NOT be there.
To automatically create this file, just start recording a "dummy" macro (with the record button on the left-bottom of a spreadsheet) and select "Personal Macro Workbook" to store it in. After recording your macro, you can open the VBA editor with [Alt]+[F10] and you will see the PERSONAL.XLSB file with the "dummy" macro.
I use this file to store loads of general macro's which are always available. I have added these macro's to my own menu ribbon.
One disadvantage of this common macro file is that if you launch more than one instance of Excel, you will get an error message that the PERSONAL.XLSB file is already in use by Excel instance Nr. 1. This is no problem as long as you do not add new macro's at this moment.
Two potential solutions below,
vbscript which can be run directly as a vbs file
A vba solution to be run from within Excel (as per Tim Williams suggestion)
vbscript solution
Dim objFSO
Dim objFolder
Dim objFil
Dim objXl
Dim objWb
Dim objExcel
Set objExcel = CreateObject("Excel.Application")
Set objFSO = CreateObject("scripting.filesystemobject")
Set objFolder = objFSO.getfolder("c:\temp")
For Each objFil In objFolder.Files
If InStr(objFil.Type, "Excel") > 0 Then
Set Wb = objExcel.Workbooks.Open(objFil.Path)
wscript.echo Wb.name
Wb.Close False
End If
Next
vba solution
Sub OpenFilesVBA()
Dim Wb As Workbook
Dim strFolder As String
Dim strFil As String
strFolder = "c:\Temp"
strFil = Dir(strFolder & "\*.xls*")
Do While strFil <> vbNullString
Set Wb = Workbooks.Open(strFolder & "\" & strFil)
Wb.Close False
strFil = Dir
Loop
End Sub
I sort of stumbled across your post just now, maybe very late, but for all future searches.
It is possible to launch your Macro by creating a .vbs file.
To do this, open notepad and add the following:
objExcel = CreateObject("Excel.Application")
objExcel.Application.Run <insert macro workbook file path, module and macro name here>
objExcel.DisplayAlerts = False
objExcel.Application.Save
objExcel.Application.Quit
Set objExcel = Nothing
save the file as follows ("your filename".vbs)
By double clicking (opening) the saved .vbs file, it will launch your macro without you having to open your excel file at all.
Hope this helps.
You could keep the macro in your personal.xls, or a masterfile, and loop through the workbooks with vba, and activate them before running your macro. As far as I know, you still have to open them with vba though.
You could use something like this:
sub LoopFiles
Dim sFiles(1 to 10) as string 'You could also read this from a range in a masterfile
sFiles(1) = "Filename1.xls"
.
.
sFiles(10) = "Filename10.xls"
Dim wb as Workbook
Dim iCount as integer
iCount = ubound(sFiles)
Dim iCount2 as integer
For iCount2 = 1 to iCount
Workbooks(sFiles(iCount2)).open
Workbooks(sFiles(iCount2)).activate
Call YourMacro
Workbooks(sFiles(iCount2)).close
next iCount2
end sub
Other way,
Sub LoopAllWorkbooksOpened()
Dim wb As Workbook
For Each wb In Application.Workbooks
Call YourMacroWithWorkbookParam(wb)
Next wb
End Sub
Sub YourMacroWithWorkbookParam(wb As Workbook)
MsgBox wb.FullName
End Sub

Resources