How to copy ActiveWorkbook name to Clipboard? - excel

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

Related

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

Copy data range from macro free workbook to another macro free workbook

I am new to VBA!
I have a workbook A that I use as a template for spinoff workbooks B, C, D, etc.
I made an error in formulas range A36:E37. I need to correct it in all the subsequently created workbooks, which can have any random name
I want to open the corrected master workbook A, and copy range from A to whateverworkbookname
Every time I use thisworkbook refrerence, it pastes the data to my personal macro workbook, same thing with activeworkbook.
I'm sure there's a simple solution, (like assigning a variable to the freshly opened workbook that needs fixing?) but I don't know how to do that.
Help is much appreciated!
Also of note, I am planning on manually opening the whaverworkbookname, then VBA unprotecting the sheet, copy paste function, protecting the sheet, saving, and closing the whateverworkbookname book when the macro completes, to be repeated with the rest of the incorrect workbooks.
If there is a smarter way to do this (which is probably way over my head) like applying a macro to all workbooks in a folder for instance, I would be interested in a point in the right direction to learn about it.
First a note:
ThisWorkbook always refers to the workbook the code is written in. This never changes.
ActiveWorkbook is the workbook that has focus (is on top). This changes easily with a mouse click on any workbook.
The issue is probably that you run the code from VBA editor. But if it is in your personal workbook and you run from the editor, then as soon as you are in the code your active workbook is the personal one because that is where your code is and if you click there to run the code it has focus.
You can check if the active workbook is the personal one
If ActiveWorkbook.Name = ThisWorkbook.Name Then
MsgBox "The active workbook is the personal one. Make sure to focus on the correct workbook."
Exit Sub
End If
'rest of your code
Create a button or link a ribbon button to launch your macro and use ActiveWorkbook in your code.

Copy worksheet from one workbook and paste to another

In my macro, I have the user open a workbook due to the name changing every month. I need the first worksheet on this now open workbook to copy and then paste into my original workbook.
I've been trying the below:
ActiveSheet.Copy After:=Workbooks("LTD_LIFE_Macro.xls").Sheets("instructions")
but keep getting an error message.

"Run Time error 9 : subscript out of range" when copying

I am trying to copy values from one sheet to another and getting this error
"Run Time error 9 : subscript out of range"
when I run the code below.
Sub updatemultiple()
Workbooks.Open ("C:\Users\akpeko.zigah\Documents\EDC\DESTINATION.xlsm")
Range("B2:F2").Copy
'Application.DisplayAlerts = False
ActiveWorkbook.Close
ActiveSheet.Paste Destination:=Worksheets(“Sheet1”).Range("B2:F2")
End Sub
Any help? I'm stuck.
There are a number of unanswered parentage questions to your workbook/worksheet/cell references but if you are pasting into the same workbook as the one containing the code then something like this should work.
Sub updatemultiple()
Workbooks.Open ("C:\Users\akpeko.zigah\Documents\EDC\DESTINATION.xlsm")
Range("B2:F2").Copy Destination:=THISWORKBOOK.Worksheets(“Sheet1”).Range("B2")
'Application.DisplayAlerts = False
ActiveWorkbook.Close False
End Sub
The problems start with how you are determining the currently active worksheet when you open the external workbook. If it was opened, the active worksheet changed then closed byt another person or process then when you opened it it is going to copy the wrong cells. If the destination worksheet is not contained in the workbook containing the code then the destination is an ambiguous reference that depends upon the current state of the application environment.
A short rewrite of your code (with some made-up references thrown in) might be like the following.
Sub updatemultiple()
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\akpeko.zigah\Documents\EDC\DESTINATION.xlsm", ReadOnly:=True)
With wb.Worksheets("Sheet1")
.Range("B2:F2").Copy Destination:=ThisWorkbook.Worksheets(“Sheet1”).Range("B2:F2")
.Close SaveChanges:=False
End With
Set wb = Nothing
End Sub
In short, be as explicit as you can by defining the workbook, worksheet and cell references for each side of every operation. Relying on 'what is active' can only lead to trouble.
If I understood your code correctly, it seems to me that you have the code in one file. When you execute the code, it opens the DESTINATION.xlsm file, copy the cells, close the DESTINATION.xlsm file, then paste the data in the active sheet of the original file that contains the code.
I don't know what data you're copying, but when you copy (manually, not in code) a lot of data from an excel file and then you close it, you get a warning:
There is a large amount of information on the Clipboard. Do you want to be able to paste this information to another program later?
For that reason, I recommend you to paste your copied cells first, and then close the file you're copying from.

Referencing workbook/sheet from another open workbook

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

Resources