Copy a range from a closed workbook to a specific sheet - excel

I am currently working on a VBA script to automate a excel sheet. The goal is to have the code open a file from using a file path in cell A2 on a sheet called Reports (the file path is dynamic and is formed using information from the sheet) , copy the data from the file for range A1:E200 and to paste the data into the original workbook on a sheet called HOURS starting at A1. At the moment i have gotten to the point where the file is opened but there is a "Mismatch" error when trying to copy the information across. Below I've attached the code used. I was hoping that someone would be able to help to make sense of the error! I am having the same problem with the close section as well. Note: I am a rookie on VBA so if you could be as clear as possible
Sub Button1_Click()
Call Test
Call Copy_Method
Call CloseWorkbook
End Sub
Sub Test()
Dim strFName As String
strFName = Sheet4.Range("A2").Value
Workbooks.Open Filename:=strFName
End Sub
Sub Copy_Method()
'Copy range to another workbook using Range.Copy Method
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb2 = ThisWorkbook
Set ws2 = wb2.Sheets("HOURS")
Set wb1 = ThisWorkbook.Worksheets("Reports").Range("A2")
Set ws1 = wb1.Sheets("Sheet")
ws2.Range("A1:E200") = ws1.Range("A1:E200").Value
End Sub
Sub CloseWorkbook()
Workbooks("venues_theeway_hours_August2020.XLS").Close SaveChanges:=True
End Sub

Have you tried this ?
ws2.Range("A1:E200").Value = ws1.Range("A1:E200").Value

You're making life quite difficult for yourself there, splitting the code out across 3 subs. Better to
rename the references to make them easier to differentiate source/destination.
keep it all together so the workbooks/worksheets can still be referenced as they're created:
Apologies if I've misread your requirements, my code does the following:
Reads the original workbook, sheet "Reports", range A2 for a filename.
Opens that filename as a 'source' workbook
Copies data from..
that 'source' workbook, sheet "Sheet", range A1:E200
..to original workbook, sheet "HOURS", range A1:E200
and then closes the 'source' workbook, unsaved as you've not made any changes.
Dim wbSource As Workbook
Dim wbDest As Workbook
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim strFName As String
Set wbDest = ThisWorkbook
Set wsDest = wbDest.Sheets("HOURS")
strFName = wbDest.Worksheets("Reports").Range("A2").Value
Set wbSource = Workbooks.Open(strFName)
Set wsSource = wbSource.Worksheets("Sheet")
wsDest.Range("A1:E200").Value = wsSource.Range("A1:E200").Value
wbSource.Close SaveChanges:=False
I'm a little puzzled about your workbook close with save? Perhaps you actually want to close the source sheet unsaved and maybe save the destination sheet you're adding data to? In that case you'll need to add this line to the end of the above code.
wbDest.Close SaveChanges:=True

Related

Open a workbook using a link and work with it

In the code below, I am trying to open an Excel file from another program and copy a value from it. I managed to get the file to open using the FollowHyperlink command, but I cannot refer to the file to copy anything from it. It seems it doesn't actually open the file until the very end of the Sub. Does anyone know how I can refer to the Excel file I'm trying to open so I can copy a value from it? I would really appreciate some help or tips.
Here is the code to open the file:
ActiveWorkbook.FollowHyperlink Address:="cdb://byname/classname/document/CDB_View/interactive?zeichnung.z_nummer=D00846554&zeichnung.z_index=01"
How can I add to it so that I can copy a value out of it?
This code doesn't work and gives an error:
ActiveWorkbook.FollowHyperlink Address:="cdb://byname/classname/document/CDB_View/interactive?zeichnung.z_nummer=D00846554&zeichnung.z_index=01"
Workbooks("D00846554-01.xlsx").Worksheets("ZACSAANA").Range("A1").Copy ThisWorkbook.Sheets(1).Range("A2")
Try something like this:
Sub RunIt()
Dim Wb As Workbook 'Your Original Workbook
Dim sh As Worksheet 'Sheet where you want to copy to
Dim Sh2 As Worksheet 'Sheet where you're grabbing data from
Dim Wb2 As Workbook 'The Workbook you are opening via hyperlink
Set Wb = ThisWorkbook
ActiveWorkbook.FollowHyperlink ("Your HyperLink")
Set Wb2 = Workbooks(ActiveWorkbook.Name)
Set sh = Wb.sheets("Sheet in Wb1")
With Wb2
Set Sh2 = Wb2.sheets("Sheet in Wb2")
'Copy values from sh2 to sh1
End With
Wb2.Close (False) 'Close Wb2 without saving
End Sub

How to use a dim as a file name inside workbooks() formula

I am trying to create a macro that will copy a range from one open sheet (Original.xlsx) to another open sheet (Destination.xlsx). The tricky part is I want the user to be able to name the origin excel filename (without the .xlsx at the end) via inputbox and I am having trouble with combining the dim with the copy function.
Dim wbdest As Workbook
Dim X As Variant
X = InputBox("Workbook from name?")
Set wbdest = Workbooks(X & ".xlsx")
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
Workbooks("destination.xlsx").Worksheets("Sheet1").Range("A2").PasteSpecial Paste:=xlPasteValues
The input box in this example will be input with "Original"
I am getting a Runtime error 9, subscript out of range on
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
Replace:
Workbooks("wbdest").Worksheets("Sheet1").Range("A2:K25").copy
with:
wbdest.Worksheets("Sheet1").Range("A2:K25").copy
(there may be other errors in your posted code)
Your be best of doing it like this;
Sub test()
Dim wb1 As Workbook 'declare the workbook
Dim wb2 As Workbook 'declare the workbook
Dim strFile As String
strFile = InputBox("Workbook from name?") 'open up input box for user to type in what workbook they want to copy
Set wb1 = Workbooks(strFile & ".xlsx") 'set the user defined workbook by name
Set wb2 = Workbooks("Destination.xlsx") 'set the destination workbook by name
wb2.Worksheets("Sheet1").Range("A2:K25").Value = wb1.Worksheets("Sheet1").Range("A2:K25").Value 'put the value from userdefined workbook into destination
End Sub
Try and avoid copy and pasting if you can :)

Change excel sheet reference from numerical sequence to sheet name

I have a relatively simple question. Currently I have some code that is working well but not efficient. I have about 500 cost centres each with their own workbook which I have consolidated into a central repository (reference - Wb2 in code below). The code copies ranges from each open template (Wb1) into my consolidation (Wb2). Sample code below (full code not necessary).
Option Explicit
Sub CopyData()
Dim Wb1 As Workbook, wb2 As Workbook, wB As Workbook
Dim rngToCopy1 As Range
Dim rngToCopy2 As Range
Dim rngToCopy3 As Range
Dim rngToCopy4 As Range
Dim rngToCopy5 As Range
Set wb2 = ThisWorkbook
Application.Calculation = xlManual
For Each wB In Application.Workbooks
If Not Left(wB.Name, 18) = "Consolidation Test" Then
Set Wb1 = wB
Exit For
End If
Next
'Forecast Data
With Wb1.Sheets(1)
Set rngToCopy1 = .Range("A11:O11", .Cells(.Rows.Count, "A").End(xlUp))
End With
wb2.Sheets(7).Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngToCopy1.Rows.Count, 15).Value = rngToCopy1.Value
wb2.Sheets(7).Range("P" & Rows.Count).End(xlUp).Offset(1).Resize(rngToCopy1.Rows.Count).Value = Sheets(3).Range("J1").Value
I have tried to simply change as an example wB2.Sheets(7) to Wb2.Sheets("Forecast_Data") as well as the original name in VBE wB2.Sheets("Sheet4") but I get a subscript out of range error?
In addition to the solution, please also provide background on why the fix is not so simple, has it got to do with how my variables are declared?
I think #GSerg already gave you the most important hint.
I assume you created a workbook with the name WB2, but it does not contain any of those sheets you want to write in.
Either create them manually in your template (WB2) or have a look at How to Add a Named Sheet at the end of all excel sheets to create them with your VBA.

Button disapear and code don't work anymore

I want to copy/past one sheet from another excel file.
Nothing hard, I have this fonction (which worked before).
But now it say that there is a problem at the "ThisWorkbook.Activate" line.
How is it possible ? The file can't find itself ?
Sub Bouton1_Cliquer()
Workbooks.Open ("the way to the excel source")
Sheets("produits").Activate
Sheets("produits").Range("A1:AZ200").Copy
ThisWorkbook.Activate
Sheets("Produits").Select
ActiveSheet.Range("A5").Select
ActiveSheet.Paste
End Sub
You can replace with the following which is faster as doesn't have the overhead of .Select and .Activate. You should also include the workbook name for the range you are copying from or set the workbook you have opened into a variable and use that. You would replace Activeworkbook with the variable.
ActiveWorkbook.Worksheets("produits").Range("A1:AZ200").Copy ThisWorkbook.Worksheets("Produits").Range("A5")
With workbook variable:
Dim wb As Workbook
Set wb = Workbooks.Open("the way to the excel source")
wb.Worksheets("produits").Range("A1:AZ200").Copy ThisWorkbook.Worksheets("Produits").Range("A5")
Another function doesn't work :
Sub UpdateData()
Dim WsDest As Worksheet 'destination workbook to write in
Set WsDest = Workbook("YES").Worksheets("maybe")
Dim WsSrc As Worksheet 'source workbook to match with
Set WsSrc = Workbook("YES").Worksheets("Perhaps")
It worked before, it is the same problem, the file can't find himself.
I tried to replace ThisWorkbook by the full name like in the exemple..
before it was :
Set WsDest = ThisWorkbook.Worksheets("maybe")
Set WsSrc = ThisWorkbook.Worksheets("Perhaps")

Excel VBA file name changes

I have to 2 Excel workbooks to work with: Book1october & Book2. Book1october18 is an import file, meaning that it changes monthly, along with the name (next month it will be Book1november18). I have to copy some data from Book1october to Book2 automatically through VBA code.
This is the code that I've written:
Windows("Book1october18").Activate
Sheets("Sheet1").Activate
Range("B2:AQ5").Select
Selection.Copy
Windows("Book2").Activate
Sheets("Sheet1").Activate
Range("R2:BG5").Select
ActiveSheet.Paste
My problem is that I don't know how to write the code in order to make the actions that I want whenever the month's name changes and also the year. (I have to make it for all the months and 2019)
You can automatically update your workbook name using the Date() function and Format()
Dim sWbName As String
sWbName = "Book1" & LCase(Format(Date, "mmmmyy"))
Debug.Print sWbName
'Prints Book1october18
The name/path of the workbook doesn't need to matter. Use K.Davis's code to come up with a filename, or prompt the user for a path/file to open - get that string into some sourceBookPath variable, then have the macro open the workbook. Now you can hold a reference to that Workbook object:
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Now, the worksheet.
Dim sourceSheet As Worksheet
If the sheet is always going to be named "Sheet1", then you can do this:
Set sourceSheet = sourceBook.Worksheets("Sheet1")
Or, if the sheet is always going to be the first sheet in the book (regardless of its name), you can do this:
Set sourceSheet = sourceBook.Worksheets(1)
Once you have a Worksheet object, you can get the Range you need - but first you need your target. Again if "book2" is opened by the macro, things are much simpler:
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Or is it created by the macro?
Set targetBook = Application.Workbooks.Add
Anyway, we want the first sheet:
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(1)
And now we can copy from the source, and paste to the target:
sourceSheet.Range("B2:AQ5").Copy targetSheet.Range("R2:BG5")
And not once did we ever need to .Select or .Activate anything, and we never needed to care for any Window.
Replace:
Windows("Book1october18").Activate
with:
s = LCase(Format(Now, "mmmm")) & Right(Year(Now), 2)
Windows(s).Activate
Try this.
This is a recognition of the next month's document, assuming you have opened two documents.
Sub test()
Dim Wb1 As Workbook, wb2 As Workbook
Dim Wb As Workbook
For Each Wb In Workbooks
If InStr(Wb.Name, "Book1") Then
Set Wb1 = Wb
ElseIf InStr(Wb.Name, "Book2") Then
Set wb2 = Wb
End If
Next Wb
Wb1.Sheets("Sheet1").Range("B2:AQ5").Copy wb2.Sheets("Sheet1").Range("r2")
End Sub

Resources