I have a loop in VBA that takes a file path from a list, attempts to open that file, and checks to see if that file has external links. I have catches for if the file is corrupt, if it is password protected, and if you need to enable editing when the code initially opens the workbook. The loop works until it gets to one particular file. Whenever the code reaches it, it pauses for about 5 seconds and then closes the workbook that has the macro running in it. I'm able to copy the file path and paste in the file explorer, so I know this particular workbook exists. Here's the start of the loop, with the rest of the code being the error catches and what to do when the code detects external links. I've tried starting the macro at this file's index number (StartNum) on the list and going line-by-line, so I'm pretty sure the problem comes at this point.
'''
Do While StartNum <= EndNum
'at this point in the loop, the activeworkbook is set to be the excel workbook running the macro
ActiveWorkbook.Save
'first error catch. ActiveFilePath is the full file pathway of the workbook I'm trying to open
On Error GoTo CorruptFile
Workbooks.Open ActiveFilePath, UpdateLinks:=0, ReadOnly:=False, Password:=""
'''
Thanks!
Related
I would like to;
obtain a list of files from a specific source folder (e.g. D:\My Drive\EM SSC\PA\AttNew)
open the first source file (all Excel files, all the exact same format)
run a macro that copies certain fields from the opened file into a data table (I already have this working for a single (named) file) on a different Excel file (C:\Users\r5\Documents\DataFile_v1.xlsx)
close the source file (an ideally delete it or move it to a different folder)
open the next source file from the list
continue until all source files are dealt with
save the data table file
New Excel source files are automatically copied into the source folder each day, so I need to open each source file, copy data to my table and then remove the files, ready for the next days files.
I have only been able to complete the steps related to copying the data fields from a single source file to the data table. I am unsure of how to do the iterative part to open one file after another. I am not an experienced VBA user. I need to open a source file, copy data from it to my table, then close/delete the source file and move on to the next source file.
Use Task Scheduler to run a bat file that runs a .vbs to open and runs macros in your excel file. Explanation and example here
The bat file will contain something along the lines of
"D:\My Drive\EM SSC\PA\AttNew\Automation.vbs"
The .vbs file would be something along the lines of
Set xlsxApp = CreateObject("Excel.Application")
xlsxApp.Visible = True
Set xlsxWorkbook = xlsxApp.Workbooks.Open("D:\My Drive\EM SSC\PA\AttNew\AutomationProject.xlsm")
xlsxApp.Run("Macro1") 'Name of your macro
Closing your workbook would contain something like this, in your ThisWorkbook VBA editor
Private Sub Workbook_BeforeClose(Cancel As Boolean) 'Closes all other
worksheets par "MainSheet", saves user time not having to delete
imported sheets everytime
For Each ws In ThisWorkbook.Worksheets
Application.DisplayAlerts = False
If ws.Name <> "MainSheet" Then 'If a worksheet is not named "MainSheet" it gets deleted
ws.Delete
End If
Next ws
Application.DisplayAlerts = True
MsgBox ("All sheets are deleted except specific sheet - After this, you
can click either 'Save' or 'Don't Save' button") 'Message box to reasure user is okay with either option when closing the file
End Sub
I am not sure about next stages, but let me know how this works so far
I have a script which downloads and creates/opens a new Excel .csv workbook of historical stock data from Yahoo Finance. I then copy the contents of worksheet(1) from that .csv workbook and create a new worksheet (at the end) in ThisWorkbook (the one containing my macro/script) and paste the data into it. I have configured my browser (Chrome) to always open .csv file downloads. Here's some sample code:
Sub Macro1()
Dim urlLink As String
Dim csvWorkbook As Workbook
urlLink = "https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=1592179200&period2=1623715200&interval=1d&events=history&includeAdjustedClose=true"
ActiveWorkbook.FollowHyperlink Address:=urlLink, NewWindow:=True
Set csvWorkbook = ActiveWorkbook
csvWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End Sub
urlLink is an example query to download historical data from Yahoo Finance in .csv format. Set your default browser to always open files of type .csv. When ActiveWorkbook.FollowHyperlink is executed, another instance of Excel will open and AAPL.csv will open. This new AAPL.csv will be the active workbook, and then the next line of code will create a new sheet in ThisWorkbook (the workbook containing your script) and copy the contents of AAPL.csv Sheet(1) into it.
My problem is that this works fine when I single step through the code but it fails when run at full speed (i.e. not in debug mode). To clarify, assuming you start with a new blank workbook, if you single step through the above code you'll get a new sheet named AAPL added to your workbook with 253 rows of data (my desired ourcome), but if you run it full speed you'll get a new blank sheet named Sheet1(2) added.
I've figured out that this is because at full speed, the new .csv file isn't getting created/open so when Set csvWorkbook = ActiveWorkbook is run there's still only 1 workbook open (ThisWorkbook) so the next code line just copies Sheet(1) of ThisWorkbook into a new sheet, instead of copying Sheet(1) from AAPL.csv into it (because it doesn't exist when that line of code is run).
Note that the name of the newly created workbook isn't always known, because if there was already an APPL.csv in that download folder it'll name the next one as APPL(1).csv and so forth, so I can't just use the name of the newly created .csv workbook to reference it as I don't know what it'll be.
So I'm asking for a way to emulate single stepping through the code in debug mode when or after ActiveWorkbook.FollowHyperlink is executed. I've tried simply putting a MsgBox after it thinking that requiring the user to click OK to continue execution would help but it didn't, and from what I read I don't think a Wait or similar thing would help either? This is similar to the issue from Pause execution of VBA script until another specific excel workbook opens?
but I don't understand the answer given in that thread and not sure if it really applies? Thanks for any help on this!
You can pass a URL directly to Workbooks.Open():
Dim wb, ws
Set wb = Workbooks.Open("https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=1592179200&period2=1623715200&interval=1d&events=history&includeAdjustedClose=true")
Set ws = wb.Sheets(1)
'run text to columns if only one column of data
If ws.UsedRange.Columns.Count = 1 Then
ws.Columns(1).TextToColumns Destination:=ws.Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Comma:=True
End If
Under this line of code, Workbooks.Open(previous_absolute_path) freezes Excel most of the time, giving no error message:
Set current_workbook = Workbooks(get_file_name(current_absolute_path))
The surounding code:
If IsWorkBookOpen((current_absolute_path)) = False Then
If previous_absolute_path <> "" And previous_absolute_path <> current_absolute_path Then
Workbooks(get_file_name(previous_absolute_path)).Close True
End If
Set current_workbook = Workbooks.Open(current_absolute_path)
previous_absolute_path = current_absolute_path
Else
Set current_workbook = Workbooks(get_file_name(current_absolute_path)) 'Causes Fail!
End If
current_absolute_path is a valid file path that is absolute. It seems every time the code runs there are windows at least being opened. However, in the newly opened workbook, no lines of code are ever executed in itsworkbook_open() from what I can tell from putting a message box as the first line of code ofworkbook_open() and the message box never appears.
The code does work, if and only if I have the workbook running this macro open, and before I run that macro, I manually open the workbook at current_absolute_path. I close that file and run the macro and it works without any problems.
current_absolute_path, is a confirmed valid file path. The line of code can open other workbooks within the same folder. Excel allows all macros and "trusts" files from the internet at this point. The folder of the workbook being opened is not protected.. and I do not have the skills yet to know where the problem is. What must be done?
EDIT: It's not manually opening the workbook that causes the Excel macro to run successfully the next time, specifically its manually closing it.
In Excel 2013: macro was working fine until today. Now, I can open the "Personal.xlsb" file, but I cannot use the Macro view button anymore, all I get is Excel in unresponding mode; and then, only way is to stop Excel entirely. When I go in design mode, I cannot access the macro registry at all (trying to do so results in the same unresponding state). I rebooted the PC entirely, did not help.
Pb seems specific to one specific "Personal.xlsb" file (I replaced the incriminated file with another "Personal" file in the XSTART folder and Excel macros worked just fine with a different .xlsb file). So I am suspecting a file corruption pb. If that is the case, is it possible to recover the original macros, or at least crack the macro file open and get a copy of the original coding?
You can try to get back your code if you manage to open the workbook from a macro in another workbook. Give this a shot:
create a folder where you will get the recovered code modules. Let's say "C:\myRecoveredCode". Put in a copy of your corrupt file "Personal.xlsb"
In Excel Options, Trust Center Settings, Check Trust Access to the VBA project object module
create a fresh workbook, copy/paste and run the following macro:
Sub TryRecovery()
myFolder = "C:\myRecoveredCode\"
Set wb = CreateObject(myFolder & "Personal.xlsb")
For Each comp In wb.VBProject.VBComponents
comp.Export myFolder & comp.Name
Next
wb.Close False
End Sub
If all goes well, you will have files a set of files that you can edit, or import to another workbook.
I do the following as a macro
Open a list of files
copy some values
Close them
After that when I exit and reopen the file that contains the macro, it also opens the files which I previously opened. even those I had used the app.workbook.close
I'm unable to find the problem out.
Where is the macro located? In a normal module?
At the end, seeing as how you've already pointed the variable at it, you may as well say
currentWB.close False
Then to close
Set currentWB = Nothing
Are there some links between the file that has the macro and the files it creates?