Referencing workbook/sheet from another open workbook - excel

I have an online report that when downloaded automatically opens as a *.csv file. I then open another Excel workbook containing various macros and want to copy the entire downloaded sheet (sheet1) over to the my main workbook either as a new sheet or into an existing blank sheet named "DATA".
My problem is referencing the open downloaded sheet as each time it is downloaded the name is different. My preference is to not save the downloaded workbook and then copy as I just delete the file when I am done.
Any help with referencing the downloaded file and activating it would be appreciated.

I've been thinking about Application.RecentFiles today and wonder if it would work here. The assumption is that the csv is the most recently opened file, i.e., it's at the top of the Home>Recent list:
Sub ActivateMostRecentOpened()
Dim WbName As String
With Application
WbName = Workbooks(.RecentFiles(1).Name, InStrRev(.RecentFiles(1).Name, .PathSeparator) + 1).Activate
End With
End Sub

Related

Is there a way to open Excel files from a folder, perform actions, then close or delete the files using a VBA macro?

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

How to pause VBA script execution until downloaded .csv file opens to allow copying worksheets between the 2 workbooks?

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

Is it possible to run a macro externally on an excel file?

Currently, I export data daily from software to excel files.
There's a lot of repetitive tasks so I created a macro.
I open the new exported excel file and then save it as "Macro-Enabled worksheet"
I open the Macro-enabled worksheet
I import the macros into the excel file
I run the macros
Is there a way to run the macro without doing all the steps above using VBS or any other way?
I don't know if there's a solution out there, but I would prefer if an external VBA operator would ask for the location of the exported file and then does the rest
You can easily open any other workbook and run any commands on that workbook. So you can have the following macro in an Excel file MyMacroFile.xlsm and manipulate data in C:\Temp\WorkbookToRunMacroOn.xlsx for example.
Option Explicit
Public Sub DoTasksOnOtherWorkbook()
'open another workbook
Dim OpenWorkbook As Workbook
Set OpenWorkbook = Application.Workbooks.Open(Filename:="C:\Temp\WorkbookToRunMacroOn.xlsx")
OpenWorkbook.Worksheets("Sheet1").Range("A1").Value = "Changed A1 in another workbook"
'don't forget to close the workbook and save or not
OpenWorkbook.Close SaveChanges:=True
End Sub
If you want to ask the user to select a file to open you can use the Application.FileDialog property it returns a file name that you can then use in the Application.Workbooks.Open to open it.

Extract a tab from a worksheet and save as a new file in a specific directory, with the file name being today's date

I'd like to copy the data from one tab in Excel, paste the data into a new worksheet, and save the new worksheet into a specific directory with today's date being the name of the newly saved file.
How can I do this using VBA?
It's going to happen every day at the same exact time. I figured I would use a combination of onTime and whatever script people help me with here.
This only needs a couple lines of code in VBA:
Sub SaveSheet1()
'This will copy the sheet and by default stick it in a new workbook
Sheets("Sheet1").Copy
'That new workbook is now the "ActiveWorkbook" so save it.
ActiveWorkbook.SaveAs ("C:\my_new_workbook" & Format(Now(), "YYYYMMDD") & ".xls")
End Sub
Instead of using the tab name which can be changed very easily by a user, I'd suggest using the sheet's codename instead.

How to copy ActiveWorkbook name to Clipboard?

The macro is supposed to open a new workbook, copy its name, and then use it within the same active workbook.
The MsgBox works just fine but copying this piece of information instead of displaying it gives me a headache.
Thanks!
MsgBox ActiveWorkbook.Name

Resources