python open the latest excel file - vba

I recently started using python 3.6 (trough Anaconda) so I am sorry if the below will result not that clear. The situation is the following:
I have an excel file, which I use to run a macro in order to obtain results from Prophet. My macro works good but, unfortunately, after several times it has been used excel reaches the limit of memory and I cannot extract the results anymore. The way to solve the problem would be to close excel and then open it again.
To do so, in the same vba macro, I open a python script that allows me to run the macro, save the excel file, close it and open it again. The macro is the below:
import win32com.client
object = win32com.client.Dispatch('Excel.Application')
object.visible=1
object.Run("Central_Run")
print("Macro ran successfully!")
print("Active WB:", object.ActiveWorkbook.Name)
for wb in object.Workbooks:
print("WB:",wb.Name)
wb.Save()
#The loop above saves all the workbooks that are open
object.quit()
#Open the Excel file again
object=win32com.client.Dispatch('Excel.Application')
wb=object.Workbooks.open(‘myfile.xlsm')
The script works, however, I would like to open the excel file, in the second part of the script, without specifying its name (wb=object.Workbooks.open(‘myfile.xlsm')), so that I can use the code for other similar excel files with different name. Ideas that I had were either to open the latest used excel file or to link the script to a specific cell in my excel file so that I need just to modify that cell instead of the script, but, unfortunately, I am not able to do it.
Thanks in advance for the help! :)

You can replace your second print statement with this:
wbName=object.ActiveWorkbook.Name
print("Active WB:", wbName)
and then replace the last line with:
wb=object.Workbooks.open(wbName)

Related

How to reference a workbook from another excel instance

I believe my problem is rather simple: I have a workbook and I'm using it to get some data from another software (SAP). When I export the data from the software, it automatically opens a .xlsx file, then what I'd need to do is copy some of the data from this file, paste on my original workbook, and then close the file. The section of my code which is giving me an error is this one:
fileName = "temp1.xlsx"
Set wbBasis = Workbooks(fileName)
This happens because the "temp1.xlsx" file that was opened by the SAP software is in another instance of excel, so my code isn't able to find it.
What I need to know is basically this. How to properly reference this "temp1.xlsx" workbook on my original code so that I'm able to edit it, copy stuff from it, close it, etc.
I've found some similar topics to my problem, like the two I'm listing down here, but couldn't adapt the solutions to my situation, and that's why I'm posting this new one.
Having multiple excel instances launched, how can I get the Application Object for all of them?
Finding a workbook in one of multiple Excel instances
Thank you in advance.
You don't need multiple instances of Excel, and you don't need the Excel file to be open in order to get information from it, either with VBA, or even with regular "linked formulas".
For example:
=SUM([C:\yourPath\Filename.xlsx]SheetName!A1:C25)
...returns the sum of cells A1:C25 on a worksheet named Sheetname in an Excel file located at C:\yourPath\Filename.xlsx.
Or you can import all the data directly with Get External Data.
See:
MSDN : Create an external reference (link) to a cell range in another workbook
MSDN : Connect to another workbook
...for more information and examples, search Google for "get data from another Excel workbook".

VBA error 1004 on Paste from CSV file with CSV file opened first

I'm a beginner on Excel VBA and working on a little tool at work. We use a tool to measure our NPS-score, and therefore I can download all our comments as CSV file. I created a VBA, to paste all these comments in an worksheet and convert it to columns and do the math.
If I open my Excel file first, then download the comments, manually copy the comments and run the script, it works fine. But if I download the comments at first, then open my Excel file and run the script, it throws a 1004 error, Method Paste of class Worksheet failed.
I've tried a lot of answers on here, but none of them seems to work. This is the part of script in the beginning to paste the comments:
Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = ThisWorkbook
wb.Activate
Sheets("Hulpblad").Visible = -1
Sheets("Hulpblad").Paste Destination:=Sheets("Hulpblad").Range("A1")
Application.CutCopyMode = False
I also tried to record a macro and use the Excel generated code, but all the answers give the same error.
Next to that, by some users of the script it doesn't matter in which order you open the files, it always throws the 1004 error. Can somebody please help :-)
1004 is an error, that is generated, when you try to change a protected sheet.
In your code, you are trying to paste a value, which cannot be done, because the sheet is protected.
Try to unprotect it first, before pasting the value and then protect it again.
I think there is no copy method in your statement. You are trying to paste the content directly

Excel workbook only shows after running code is finished

I have a program in an Excel workbook that opens a Powerpoint-File, updates the links within this file and closes it after that. This works fine. Here is my problem: When the links are updated an Excel file with the source data is opened. After Powerpoint is closed this file stays open. I want it to get closed because I repeat this process for many files and I can't end up with hundreds of open Excel files.
I tried the following:
WBKs=Application.Workbooks.count
For i = WBKs to 1 Step -1
If Workbooks(i).Name<>ThisWorkbook.Name then
Workbooks(i).close savechanges:=False
End if
Next i
Now comes the weird part. Whenever I just run my code, WBKs always returns 1 and the Excel file only pops up after the code is finished. If I go through my code in debug mode it works. The workbook pops up as soon as I enter debug mode.
I tried Applicatio.Wait in the hope that the file would show after a second. The file only showed after the code was finished.
I tried a Do While Loop to wait until the file is open. Excel crashes because I never leave the loop.
Edit: I tried DoEvents as suggested. Does not work either.
This is just a workaround, but try using a brute force after x times your macro has run. Store that x somewhere in workbook, save. And kill excel process (all instances, including self) :
Dim sKill As String
sKill = "TASKKILL /F /IM excel.exe"
Shell sKill, vbHide
Found here : VBA script to close every instance of Excel except itself
When running your macro next time, you will use that x as a starting point for next PPT file to update.

Automate process by running excel VBA macro in SSIS

Recently, I have a project need to automate a process by combining SSIS package and excel VBA macro into one. Below are the steps:
I have a SSIS package exporting all the view result to multiple individual file from sql server to excel. All the files are saved in same location.
I have one excel VBA macro perform cleaning to remove all the empty sheets in each exported excel file.
I also have a excel VBA macro perform merging task to merge all the excel file into in master excel file. This master excel file contains all the result set and each result set saved on different tabs accordingly.
Since I am manually running step 2 and step 3, so my question is how should connect step 2 and step 3 with step 1 to combine them as one automate process.
Please provide me advice on how likely this can be achieved! Thanks a lot.
The way to do this is to create a script task in your SSIS package.
Then, once inside the script task, you can call the Excel interop through the C# code of the script task. e.g. you can add a reference to Microsoft.Office.Interop. Once you are using that library in your C# code of the script task, you can add some code that will call the macro. e.g.
oExcel = CreateObject("Excel.Application")
oExcel.Visible = False
oBooks = oExcel.Workbooks
oBook = oBooks.Open(Dts.Variables("filePath").Value.ToString())
//Your macro here:
oExcel.Run("Yourmacro")
Then you could write code for the other workbooks aswell, for whatever automation you need after this - e.g. you can close the workbook and open another workbook, through the Excel automation as needed.

How read only another file in excel vba without open it

I have two files. In the first i wrote a macro that takes as input the second file and open it to read its datas. The problem is that every time i launch the macro the second file open and i don't want that. I think the problem is this:
path = "C:\Users\Me\Desktop\example.xls"
Set openWb = Workbooks.Open(path)
The Workbooks.Open(Path) that open the file. How can i solve the problem? I need only take the example.xls file and read its data without open that file in summary. Thanks a lot