Copy and Paste between different Excel instances - excel

I bought a software (with a large database), and its output is a simple Excel workbook, not saved anywhere (no path), named generically "Book1", that simply pops up on my screen.
Every time I ask the software for this output, I need to copy the content of this workbook and paste into another workbook, a mother-workbook, as I named it, to consolidate all the data.
I have to repeat this action dozens of times a day, so I thought it would be a great idea to create some VBA code to automate this task.
So... I made a very simple one:
ActiveWorkbook.ActiveSheet.Range("A1:C32").Copy
Workbooks("Mother-Workbook.xlsm").Worksheets("Sheet1").Range("B6:D37").PasteSpecial Paste:=xlPasteValues
The problem is... Each time the software outputs a new workbook, it seems that it is created in a new instance of Excel, which my macro can't reach. I mean, I run the code, but nothing happens, because my mother-workbook doesn't find the generic, unsaved and located in another excel instance "Book1".
If I open the mother-workbook after the output is opened, OK, the code works, because both are in the same instance. But as I need to keep the mother-workbook open all the time, I can't do this. I don't want to save each new output file either. It would take me a lot of time.
I'm using the 2016 version of Excel, but already tried the 2010 as well. My OS is Windows 10 Pro.
Any thoughts?

This code should do it.
Dim xlapp As Object
Set xlapp = GetObject("Book1").Application
xlapp.ActiveWorkbook.ActiveSheet.Range("A1:C32").Copy
Workbooks("Mother-Workbook.xlsm").Worksheets("Sheet1").Range("B6:D37").PasteSpecial Paste:=xlPasteValues
xlapp.DisplayAlerts = False
xlapp.Quit
Note that you need to close "Book1" at the end of your code to make sure that the next time an Excel file is created it will also be called "Book1" and not "Book2". And might as well close the Excel instance while we are at it!
For more information on the GetObject function, you can have a look at this page

Thanks a lot, DecimalTurn and Patrick Lepelletier!
The GetObject really helped me. The "closing" command worked better like this:
Sub CollectA()
Dim oApp As Application
Dim oWb As Workbook
Set oWb = GetObject("Book1")
Set oApp = oWb.Parent
oWb.ActiveSheet.Range("A1:C32").Copy
Workbooks("Mother-Workbook.xlsm").Worksheets("Sheet1").Range("B6:D37").PasteSpecial Paste:=xlPasteValues
oWb.Close False
oApp.Quit
End Sub
Cheers!

Related

How to deal with co-authoring while editing an Excel file in Sharepoint via VBA

I have an excel file stored in Sharepoint (which is also accessible with Microsoft Teams), with the path: https://organization.sharepoint.com/PathOfFile/myFile.xlsx
The file can be edited by multiple at the same time with the co-authoring feature in Sharepoint.
I want to use another excel file stored locally in my computer to access and modify the one in Sharepoint. This local file has a button with this VBA code in it:
Sub UpdateSP():
f_name = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
Workbooks.Open f_name
Workbooks("myFile.xlsx").Activate
ActiveWorkbook.Sheets("sheet1").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.Value = 9999
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = 0000
ActiveWorkbook.Close SaveChanges:=True
End Sub
In principle it works, the file in Sharepoint is modified. But things go wrong if there's someone editing the file while I run the code, then two versions of the file seem to be created, one for the online-live editing, and the one for my code.
If this happens, the online version of the file won't show the changes made by the code, and whenever the file is opened with the excel app, a pop-up will show asking which version of the file should be kept, losing all the changes done in the disposed version.
I have tried to use the CanCheckOut and CheckOut methods, but CanCheckOut always returns False for whatever reason (there are some questions here with the same issue but I havent been able to find a solution).
Can someone suggest a solution to this issue? Thanks.
I'm not 100% sure it will work on SharePoint, but in theory, ADODB is a library for VBA that has the syntax of objects to use Microsoft's Jet Engine so you can open files AdLockOptimistic---ally. ((look up lock types in ADO.net))
This works on a file directory basis, so if the DB being modified is open, it will handle the update.
Instead of using Excel's Application to open the file, you would establish an ADO connection, and then specify the type of Lock in order to access the Excel's sheets and tables inside it.
This works for shared / network drives, so I'm guessing since SharePoint can be mapped as a file explorer drive, then ADO should work and is worth a try.
Here's a basic example to get you started: ADO question
Try enabling the autosave after activating the workbook.
To do so, add this line:
ActiveWorkbook.AutoSaveOn = True
after the Workbooks("myFile.xlsx").Activate line.
I have had similar issues with collaborative files and making sure the autosave is enabled has solved it.
To be able to incorporate changes that way your code must run inside a coauthoring context.
Instead of opening the document from another doc or local copy, the code must be running inside the same document being opened from the same source URL (Sharepoint or OneDrive), that way the add-in or macro can make changes that Excel itself will handle on a coauthoring context.
I recommend taking a look at Coauthoring in Excel add-ins of the Office Dev Center, including the linked articles inside (specifically "coauthoring", redirecting to the support center, and "About coauthoring in Excel (VBA)" at the bottom with more samples).
CanCheckOut will always return false if a workbook is open. Thus you must check before you touch it. The CheckOut command will not open the file so we must also have an open statement after CheckOut.
Using your example it would look like this;
Option Explicit
Public Sub UpdateSP()
Dim fName As String
fName = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
If Workbooks.CanCheckOut(fName) Then
Workbooks.CheckOut fName
Dim myFile As Workbook
Set myFile = Workbooks.Open(fName)
Dim mySheet As Worksheet
Set mySheet = myFile.Sheets("Sheet1")
Dim startRange As Range
Set startRange = mySheet.Range("A" & mySheet.Rows.Count).End(xlUp).Offset(1)
startRange.Value = 9999
startRange.Offset(0, 1).Value = 0
myFile.Close SaveChanges:=True
Else
MsgBox fName & " can't be checked out at this time.", vbInformation
End If
End Sub

Activate Workbook WITHOUT filename but using the extension

I have slowly learning some VBA by searching them through google, this site has the best format for understanding the answers. I have been able to really automate many of my reports but have hit a wall in searching out this function.
I have a many reports and we use a web interface to generate specific data. the file names are always randomly generated when exported, but they are always (read only) .xls files.
I have tried other VBA commands that i have searched heavily but none work. using the "*.xls" doesnt seem to work. these have no file path, but are the only .xls workbook open when running this report.
I would appreciate any assistance.
Welcome to SO.
In your question you say have no file path, but are the only .xls workbook open when running this report.
If this is true (the .xls workbook you want is the ONLY one opened at this time), then this code may work for you.
It will loop trough each opened workbook and check the extension of the file. If it is XLS then it will activate it.
Dim f As FileSystemObject
Set f = New FileSystemObject
Dim WB As Workbook
For Each WB In Application.Workbooks
If f.GetExtensionName(WB.FullName) = "xls" Then
WB.Activate
'rest of your code
End If
Next WB
Set f = Nothing
To make this code work, you need to activate a reference:
In the VBA Editor, go to TOOLS-> REFERENCES and search for Microsoft Scripting Runtime
Hope this can help you

Excel Macro Stored in Access

So I'm importing data every day into Access to use for reporting. The data comes from several spreadsheets created by different individuals. Because those individuals like to format things incorrectly I created a macro that reformats their document so that it can be imported cleanly into Access for me to use. Works great but it gets tedious having to open up each Excel sheet to run this Macro.
What I'm trying to do is place the Excel Macro in Access and then run the formatting code before importing it all at once. I am a bit lost in approaching this. I'm aware of ways to run Macros already placed in Excel sheets but is there a way to run a macro that is stored in Access that works in excel. I also thought to maybe inject the Macro into the excel document and then run it.
To sum things up, what I'm hoping to do is from Access, store a macro, that can be used to alter Excel Files.
Is this at all possible? If so How? Is there another approach?
What you are asking to do is automate Excel from Access. Yes, you can do this. In Access, add a module, add a reference to the Microsoft Excel object model (Tools: References), and use this framework code to get you started:
Sub PrepExcelFileForImport()
Dim xl As Excel.Application
Dim wbk As Excel.Workbook
Dim wst As Excel.Worksheet
Set xl = CreateObject("Excel.Application")
With xl
.Visible = True
Set wbk = .Workbooks.Open("c:\temp\temp.xlsx")
Set wst = wbk.Worksheets("data")
With wst
' add your formatting code here, be sure to use qualified references, e.g.
.Rows(1).Font.Bold = True
End With
End With
wbk.Close SaveChanges:=True
xl.Quit
End Sub

Excel Macro: Open Sheet in Background and Execute Analysis in Background Sheet

I am relatively new to the true power in Excel - Macros/VBA and have been tasked to set up the financial model for a million dollar project. I am able to set everything up and have it run smoothly, but there's too much manual input involved. I would like to seek simplification through the power of VBA.
This is my dilemma:
I need to be able to individually double-click on a specific set of cells (in a Row), which will open up a file window that allows me to select a EXL file.
Once I select the file, that file should be preferably opened in a temp status (not visible, but I can run functions and pull info from it).
I will then need the macro to go into that opened sheet, conduct a simple SUMIFS function, and record the outcome in a column of the current sheet I'm working from.
I've been doing some Excel tutorial on Lynda in hope to seek the answers there, but I think the complexity of this request demands the knowledge of a true master.
Any help will be greatly appreciated! I would imagine this could be a nice little challenge for those who seek it :)
Sincere thanks,
Try this:
Dim appExcel As Excel.Application
Set appExcel = CreateObject("EXCEL.Application")
Dim wkbk As Excel.Workbook
Set wkbk = appExcel.Workbooks.Open(sPathSrc, , False, , , sPassword)
' do EXCEL work here
If Not wkbk Is Nothing Then wkbk.Close True
Set wkbk = Nothing
If Not appExcel Is Nothing Then
appExcel.DisplayAlerts = False
appExcel.Quit
End If
Set appExcel = Nothing
This code is from an ACCESS application that invoked EXCEL to print some reports. I found it necessary to sprinkle some DOEVENTS calls around, but it was all a while ago; some details escape me at this moment.

Unhide Excel Application Session

I have an Excel VBA method (I didn't write it) that runs and one of the first things it does is hide the Excel session Application.Visible = False.
However, when the method has finished, it does not unhide the Excel session so it remains open and listed in the Task Manager but is hidden and seemingly unusable.
Does anyone know, without have the VBE open (so one can access the Immediate Window and run Application.Visible = True), how to unhide this Excel session? At the moment, I'm simply having to kill the session using the Task Manager.
This isn't a massive deal but I'm just interested if anyone knows how to resurrect such a session.
Like I said, it's not a big deal but was just interested if anyone knew of shortcut key or anything to bring it back.
There is no shortcut as such that I am aware of but you can do this.
Open MS Word and paste this code in the VBA Editor. Close all open instances of Excel which are visible and then run and this code. This will make a hidden instance visible. Manually close the instance and repeat the process if there are more instances.
Option Explicit
Sub Sample()
Dim oXLApp As Object
'~~> Get an existing instance of an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
On Error GoTo 0
oXLApp.Visible = True
Set oXLApp = Nothing
End Sub
I am not deliberately using a loop as the hidden instance can have a workbook which you might like to save?
If you want you can convert the above code to a VB Script document which you can directly run from the desktop.
Unfortunately, I don't have the control to make the changes required.
What do you exactly mean? Is the VBA Password Protected? If no then my suggestion is still the same as earlier
This is a case of poor programming. Even if we give a code to close
all hidden Excel instances, that won't help you. Because next time you
run that macro, you will face the same problem again. Why not edit the
existing code and add Application.Visible = True at the end? Is the
VBA password protected? – Siddharth Rout 28 mins ago
A good solution!
Open up Word, assuming you have it, and open the VBA Editor there, then open the Immediate Window (Ctrl+G) and type:
Getobject(, "Excel.Application").Visible = true
and press enter.
I had a similar problem and solved it with code line reordering.
Look for a line like this ActiveWorkbook.Close that might be the reason you cannot unhide the session.
If you can find it, put Application.Visible = True just before it and voila.
as code:
sub runthis()
dim xl as object
set xl = new excel.application 'create session
xl.workbooks.open filename:= "«yourpath»" 'open wb in the new session
xl.visible=true 'this is what you need, show it up!
'rest of the code
end sub
No need for word macro at all.
Open up another excel workbook.
Hit Ctrl+F11 to go to the VBA editor and there yoy will see the running but hidden excel file on the left.
Search the code of the hidden application file for Application.Visible = False and comment it out. Save and restart the file.
Alternatively you can get back the application to show without closing if you type Application.Visible = True in the immediate window (Ctrl+G)

Resources