Loading a worksheet from another workbook into Excel with VBA - vba

I am attempting to create a subroutine that prompts the user to select a workbook and then adds the first worksheet of the selected workbook as a tab in the existing (active) workbook. Then names the new tab "Data". Here is the code I am using so far:
Sub getworkbook()
' Get workbook...
Dim ws As Worksheet
Dim filter As String
Dim targetWorkbook As Workbook
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
ws = Application.GetOpenFilename(filter, , caption)
ws.Add After:=Sheets(Sheets.Count)
ws.Name = "DATA"
End Sub
This code doesn't seem to be working and is returning the following error:
"ws.Add" method or With Block not set.
Any help is appreciated.
Thanks,

You have declared ws as a worksheet and GetOpenFilename is returning a File name. I would recommend reading my post in this link:
Is this what you are trying?
Note: I have not done any error handling. I am sure you can take care of that.
Sub getworkbook()
' Get workbook...
Dim ws As Worksheet
Dim filter As String
Dim targetWorkbook As Workbook, wb As Workbook
Dim Ret As Variant
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
Caption = "Please Select an input file "
Ret = Application.GetOpenFilename(filter, , Caption)
If Ret = False Then Exit Sub
Set wb = Workbooks.Open(Ret)
wb.Sheets(1).Move After:=targetWorkbook.Sheets(targetWorkbook.Sheets.Count)
ActiveSheet.Name = "DATA"
End Sub

Related

Error Select Method of Range Class Failed

My code aims to import an .xls file selected by the user, and copy and paste it into my Data sheet in Book 1. This Book 1 has 2 sheets: Results and Data.
I want to run the code when I am in Results and here comes the problem.
When I run it in my Data sheet, after clearing the current sheet (Data) the file is imported and copied well.
However, when I import it when I am in the Results sheet, it comes an error according to the MsgBox Err.Description
What's wrong in the code?
Sub ImportData()
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim wb As Workbook
On Error Resume Next
Set wb = Application.Workbooks("Book1.xlsm")
wb.Activate
wb.Sheets("Data").Range("A1:M5000").Select
Selection.ClearContents
Sheets("Data").Select
Range("A1").Select
Set targetWorkbook = Application.ActiveWorkbook
filter = "Text files (*.xls),*.xls"
caption = "Please Select an Input File "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.ActiveSheet
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.ActiveSheet
sourceSheet.UsedRange.Copy targetSheet.Range("A1")
sourceSheet.UsedRange.Value = sourceSheet.UsedRange.Value
targetSheet.Paste
customerWorkbook.Saved = True
customerWorkbook.Close
Sheets("Results").Select
End Sub
You may try it like this...
Sub ImportData()
Dim filter As String
Dim caption As String
Dim customerFilename As Variant
Dim customerWorkbook As Workbook, targetWorkbook As Workbook
Dim targetSheet As Worksheet, sourceSheet As Worksheet
Set targetWorkbook = Application.Workbooks("Book1.xlsm")
Set targetSheet = targetWorkbook.Sheets("Data")
targetSheet.Range("A1:M5000").ClearContents
filter = "Text files (*.xls),*.xls"
caption = "Please Select an Input File "
customerFilename = Application.GetOpenFilename(filter, , caption)
If customerFilename = False Then
MsgBox "No Customer File was selected.", vbExclamation
Exit Sub
End If
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
Set sourceSheet = customerWorkbook.ActiveSheet
sourceSheet.UsedRange.Copy
targetSheet.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = 0
sourceSheet.UsedRange.Value = sourceSheet.UsedRange.Value
customerWorkbook.Saved = True
customerWorkbook.Close
targetWorkbook.Sheets("Results").Select
End Sub
The following code:
wb.Sheets("Data").Range("A1:M5000").Select
Selection.ClearContents
Should be replaced with:
wb.Sheets("Data").Range("A1:M5000").ClearContents
The same goes for all similar lines. Operating on selection most often comes from macro recorder, is a very unreliable and slow method. It's dependent on currently selected range or object and non-transparent in the code, as it forces to know what is currently selected / active.
Selecting should be done only to leave selected worksheet or cell active in the end of macro operation or to perform actions on ActiveWindow.
Likewise, try to eliminate ActiveSheet:
Set targetSheet = targetWorkbook.ActiveSheet
And replace it with one of the following examples:
Set targetSheet = targetWorkbook.Worksheets(1) '1st worksheet in the file
Set targetSheet = targetWorkbook.Worksheets("myData") 'worksheet named "myData"

Unprotect sheet/Workbook

I managed to get this working but some of my client files are protected.
Sub VBA_Read_External_Workbook()
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim sheet As String
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsb),*.xlsb"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
sheet.Unprotect ("CADDRP")
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(3)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("D85", "D95").Value
' Close customer workbook
customerWorkbook.Close
End Sub
I squeezed sheet.unprotect inside.
It gives me an error
"Object Required" Run time error '424'.
I'm guessing I missed some variable declaration in the process?
Assuming you need to Unprotect the Sheet, not the Workbook.. Remove the sheet.Unprotect line where you have it currently and put it back in after setting the SourceSheet:
Set sourceSheet = customerWorkbook.Worksheets(3)
sourceSheet.Unprotect ("CADDRP")

File copies and pastes blank data (or does not even copy and paste). Also loading is long

can someone please tell me why the data is not copying and pasting (or why it is copying and pasting blank data? Also is there a way to speed the automation?
Sub GetDataCopyPaste()
Dim wbTarget As Workbook 'where the data will be pasted
Dim wbSource As Workbook 'where the data will be copied
Dim StrName As String 'name of the source sheet
Application.ScreenUpdating = False 'these statements help performance by disabling the self titled in each, remeber to re-enable at end of code
Application.DisplayAlerts = False
Set wbTarget = ActiveWorkbook 'set to the current workbook
StrName = ActiveSheet.Name 'get active sheetname of workbook
Set wbSource = Workbooks.Open("C:\Users\jjordan\Desktop\Test Dir\Test File Test\metrics list.xlsx") 'opens Target workbook
Set wbTarget = Workbooks.Open("C:\Users\jjordan\Desktop\Test Dir\MASTER\Weekly Logbook - 2016.xlsm") 'opens Source workbook
wbSource.Sheets("IOS").Range("A1:E60").Value = wbTarget.Sheets("Sheet6").Range("A1:E60").Value 'copy & pastes source data onto Target workbook
wbTarget.Save 'save workbook
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
This line is backwards
wbSource.Sheets("IOS").Range("A1:E60").Value = wbTarget.Sheets("Sheet6").Range("A1:E60").Value 'copy & pastes source data onto Target workbook
You need
wbTarget.Sheets("Sheet6").Range("A1:E60") = wbSource.Sheets("IOS").Range("A1:E60").value
I just tested and succeeded
Option Explicit
Sub test()
Dim myWB As Workbook
Set myWB = Workbooks.Open("C:\Users\raystafarian\Downloads\Book3.xlsx")
Dim yourWB As Workbook
Set yourWB = Workbooks.Open("C:\Users\raystafarian\Downloads\Book2.xlsm")
myWB.Sheets("Sheet1").Range("C1:C4").Value = yourWB.Sheets("Sheet1").Range("A1:A4").Value
End Sub

Runtime Error 9 - Subscript Out Of Range

I'm trying to create a form based interface using the VBA. I ran into a problem which I cannot figure it out. So in my code, I try to create a new workbook then save it. After that it will scan through the checkbox and see which one is getting selected. If it get selected, it will create a new sheet and copy the pre-made template. The user will open another workbook that they want and it will copy the information from that workbook to the workbook that just made. Here is the code for retrieving the data:
Sub mil10_data()
Dim NewWB As Workbook
Dim thisWB As Workbook
Dim wb As Workbook
Dim Ret
Set thisWB = ThisWorkbook
Set NewWB = ActiveWorkbook
With NewWB
'Copy the pre-made template to new workbook
thisWB.Sheets("Data 10").Range("A1:AZ3000").Copy NewWB.Sheets(ActiveSheet.Name).Range("A1:AZ3000")
'Retriving the data
Ret = Application.GetOpenFilename("Excel Files (*.CSV), *.CSV", Title:="Select File To Be Opened")
If Ret = False Then Exit Sub
Set wb = Workbooks.Open(Ret)
**'This is where the error is show up
wb.Sheets(ActiveSheet.Name).Range("E21:E2136").Copy NewWB.Sheets(ActiveSheet.Name).Range("C2:C2117")**
wb.Close SaveChanges:=False
Set wb = Nothing
Set NewWB = Nothing
End With
End Sub
I figure that maybe because there are three workbooks open, it didn't know which one is the active workbook, but that is not the case. I tested by using the MsgBox and it display the right workbook and worksheeet name that I want. If I change the ActiveSheet.Name to the actual sheet name, it works, but I don't want to use that method. I have different worksheets that need to be created, so I prefer using the ActiveSheet.Name. Anyone know why it didn't work? I would really appreciate the help. Thank you!
ActiveWorkbook and ActiveSheet are really clumsy ways of getting user input. You should save in variables the properties that are you interested in (as soon as possible), and then stop referring them directly.
In your case, the code may look like
Sub mil10_data()
Dim NewWB As Workbook
Dim thisWB As Workbook
Dim wb As Workbook
Dim Ret
Dim active_sheet_name As String
Set thisWB = ThisWorkbook
Set NewWB = ActiveWorkbook
Let active_sheet_name = Application.ActiveSheet.Name
With NewWB
'Copy the pre-made template to new workbook
thisWB.Sheets("Data 10").Range("A1:AZ3000").Copy NewWB.Sheets(active_sheet_name).Range("A1:AZ3000")
'Retrieving the data
Ret = Application.GetOpenFilename("Excel Files (*.CSV), *.CSV", Title:="Select File To Be Opened")
If Ret = False Then Exit Sub
Set wb = Workbooks.Open(Ret)
wb.Sheets(active_sheet_name).Range("E21:E2136").Copy NewWB.Sheets(active_sheet_name).Range("C2:C2117")
wb.Close SaveChanges:=False
Set wb = Nothing
Set NewWB = Nothing
End With
End Sub
If you still get "Subscript out of range" error, that means that you either don't select correctly the ActiveSheet before running the script, or that sheet does not exist in the workbook wb.

VBA Open any workbook

I have a macro that opens a spreadsheet from a specific folder and saves the output to a worksheet called Sheet1 in another workbook. The macro works if the file name is called "MyFile.xls" but i would like it to be able to run on any file name but it must have a "Book2" worksheet.
Here is my code:
Dim source As Workbook
Dim output As Workbook
Dim sourceSheet as WorkSheet
Dim outputSheet as WorkSheet
Dim file As String
file = "C:\Spreadsheets\MyFile.xls" 'I would like it to handle any files from any location'
Set output = ThisWorkBook
output.Activate
If Len(Dir$(file)) > 0 Then
Set source = workbooks.Open(file)
Set sourceSheet = source.Worksheets("Book2") 'Must only run if the sheet is called Book2'
Set outputSheet = output.Worksheets("Sheet1") 'Saves sheets into a new sheet called Sheet1'
End Sub
Is this what you are trying? (TRIED AND TESTED)
Sub Sample()
Dim source As Workbook, output As Workbook
Dim sourceSheet As Worksheet, outputSheet As Worksheet
Dim File
'~~> Show a dialog to open any excel file
File = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*")
If File = False Then Exit Sub
Set output = ThisWorkbook
If Len(Dir$(File)) > 0 Then
Set source = Workbooks.Open(File)
'~~> Error check to see if the workbook has that sheet
On Error Resume Next
Set sourceSheet = source.Worksheets("Book2")
If Err.Number = 0 Then
Set outputSheet = output.Worksheets("Sheet1")
'
'~~> Rest of your code
'
Else
MsgBox "Not found"
source.Close SaveChanges:=False
End If
On Error GoTo 0
End If
End Sub