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
Related
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
I need to copy a couple of excel sheets ("Y", "X") from one file to the same sheet in another excel file (call it Z - the same file that I'm using the VBA on).
my limitation is that the name and path of the first excel file (with the X,Y) are changing, therefore I'm trying to write something more generic using the "as String" and the Application.GetOpenFilename() command but I'm receiving an error.
Tried to separate into 2 different subs
Sub BrowseForFile()
Dim sFileName As String
sFileName = Application.GetOpenFilename(, , "open the file: " )
If sFileName = "false" Then Exit Sub
MsgBox sFileName
Workbooks.Open (sFileName)
Workbooks(sFileName).Sheets("X").Activate
Stop
Runtime Error 9
file doesn't find (1004 I think)
If the user presses the Cancel button then the GetOpenFilename function returns a boolean False not a string "false" so you need to test for If sFileName = False Then and declare it as Variant.
If you open a workbook always reference it to a variable so you can use that to access the workbook easily
Dim OpenedWb As Workbook
Set OpenedWb = Workbooks.Open(sFileName)
Then you can use the variable Wb to reference the workbook you opened
OpenedWb.Worksheets("X").Activate
Note that using .Select and .Activate is a bad practice and should be avoided (How to avoid using Select in Excel VBA). Instead use another reference to reference your workbook.
Dim ws As Worksheet
Set ws = OpenedWb.Worksheets("X")
And access a range like ws.Range("A1").Value for example.
Sub BrowseForFile()
Dim sFileName As Variant 'needs to be variant because cancel returns a boolean False
sFileName = Application.GetOpenFilename(, , "open the file: " )
If sFileName = False Then Exit Sub
MsgBox sFileName
Dim OpenedWb As Workbook
Set OpenedWb = Workbooks.Open(sFileName)
Dim ws As Worksheet
Set ws = OpenedWb.Worksheets("X")
MsgBox ws.Range("A1").Value 'output the value of `A1` in worksheet `X` of workbook `sFileName`
End Sub
With an already-opened workbook, I want to create a copy of a worksheet ("Template") and re-name it with the value I have in an array. When I debug the code the copy is created when I execute the line but I still get an error 424: object required.
I've tried On Error Resume Next but since I already used On Error GoTo in my sub it isn't read.
Dim oXL As Excel.Application 'Requires loading "Microsoft Excel 16.0 Object Library" from Tools -> References
Dim oWB As Excel.Workbook
Set oXL = New Excel.Application
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn) 'Opens Excel
oXL.Visible = True 'Shows Excel window while running code. Set to false after finished editing.
Dim ws As Worksheet
For i = LBound(seller_names) To UBound(seller_names)
'On Error Resume Next 'Doesn't work
Set ws = oXL.ActiveWorkbook.Sheets("Template").Copy(After:= _
oXL.ActiveWorkbook.Sheets(oXL.ActiveWorkbook.Sheets.Count))
ws.name = seller_names(i)
Next i
Sheets.Copy doesn't return a reference to the copied sheet, so you need to first copy the sheet, then get a reference to it:
With oXL.ActiveWorkbook
.Sheets("Template").Copy After:= .Sheets(.Sheets.Count)
Set ws = .Sheets(.Sheets.Count)) '<< get the copy
ws.name = seller_names(i)
End With
On Error Resume Next should always work - but is not always a good solution - unless you have "Break on all errors" enabled in your VBA Options.
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")
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