MS EXCEL VBA - I need to import a worksheet from one excel file to another - vba

I need to import a worksheet from one excel workbook (worksheet name is not always the same) and import it into the current active workbook.
Here is what I have so far:
Sub openFile_Click()
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.rpt (*.rpt),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Workbooks.Open Filename:=FileToOpen
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ActiveWorkbook
wb2 = Workbooks(FileToOpen) 'This is where I am stuck..I can't give it a static name
For Each Sheet In wb1.Sheets
If Sheets.Visible = True Then
Sheets.Copy After:=wb2.Sheets(wb2.Sheets.Count)
End If
Next Sheet
End If

This code will work for what you want you want. I made the following corrections.
Move all declarations of variables to beginning of procedure so they are declared before you use them. It is just good practice.
Assign your Active Workbook to the variable before you open the second workbook so there is only one workbook open.
Your for each statement had a few corrections as well.
Sub openFile_Click()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ActiveWorkbook
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.rpt (*.rpt),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
If Sheet.Visible = True Then
Sheet.Copy After:=wb1.Sheets(wb1.Sheets.Count)
End If
Next Sheet
End If
End Sub

Set the Workbook on open, (or set the workbook later without the filepath)
Here you go:
Sub openFile_Click()
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.rpt (*.rpt),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ActiveWorkbook
Set wb2 = Workbooks.Open(FileToOpen)
For Each Sheet In wb1.Sheets
If Sheet.Visible = True Then
Sheets.Copy After:=wb2.Sheets(wb2.Sheets.Count)
End If
Next Sheet
End If
End Sub

Related

VBA open file in active worksheet

I am trying to create a code to open an Excel file (CSV file actually) in the active worksheet of a workbook. The file is not always located on the same location and does not always have the same name. Therefore I want the user to be able to browse the file.
I tried the code shown below. The code works partially, the code now opens the file in a new workbook. However, I would like to open the file/get the data in the active worksheet. Do you know how I could change the code to do this?
Sub OpenFile()
Dim FileName As String, test As Workbook
On Error GoTo ErrorMessage
FileName = Application.GetOpenFilename(, , "Browse for workbook")
'Open workbook
Workbooks.Open FileName
Set test = ActiveWorkbook
Exit Sub
ErrorMessage:
MsgBox ("Je hebt geen bestand geselecteerd, probeer het nogmaals.")
End Sub
You could just open the file copy the cells to the target worksheet.
Sub OpenFile()
Dim FileName As String
FileName = Application.GetOpenFilename("Comma Separated Values,*.csv", , "Browse for workbook")
If FileName = "False" Then Exit Sub
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ActiveSheet
Application.ScreenUpdating = False
With Workbooks.Open(FileName)
ActiveSheet.UsedRange.Copy TargetWorksheet.Range("A1")
.Close SaveChanges:=False
End With
End Sub
You could open the workbook the user selects and copy whatever sheet you need into your current workbook. Edit: This will paste it into your active sheet using UsedRange as others have shown.
Sub OpenFile()
Application.ScreenUpdating = False
Dim FileName As String, test As Workbook
Dim shActive As Worksheet
On Error GoTo ErrorMessage
FileName = Application.GetOpenFilename(, , "Browse for workbook")
'Open workbook
Set shActive = ActiveSheet
Set test = Workbooks.Open(FileName)
'copy the sheet you need from that workbook into your current workbook
test.Sheets(1).UsedRange.Copy shActive.Range("A1")
'close the previous workbook
test.Close SaveChanges:=False
Exit Sub
ErrorMessage:
MsgBox ("Je hebt geen bestand geselecteerd, probeer het nogmaals.")
End Sub

VBA Copy Method keeps failing?

I could have sworn that this was working before - but for some reason, this doesn't appear to be working anymore. I'm trying to take the active worksheet (also, this may not be very pretty or clean, but I am still really new to VBA), copy it to a new worksheet, in the new worksheet I want to open the Excel save as dialog, and when the worksheet is saved (in CSV) format, I want the workbook to close (or even if it doesn't close) at least return the user to the original workbook and end the sub
Sub saveExportAs()
Application.CutCopyMode = False
Sheets("load").Select
ActiveWorkbook.Activate
Sheets("load").Copy
Dim varResult As Variant
Dim ActBook As Workbook
'display the save as dialog
varResult = Application.GetSaveAsFilename(InitialFileName:="\\network\folder\upload_" & Format(Date, "yyyy-mm-dd") & ".csv", FileFilter:= _
"Comma Delimited / Upload Files (*.csv),*.csv", Title:="Save Upload File")
'check to make sure the user didn't cancel
If varResult <> False Then
ActiveWorkbook.saveAs Filename:=varResult, _
FileFormat:=xlCSV
Exit Sub
End If
End Sub
you can use the sheets defined as workbook/worksheet to avoid issues... may be like this :
Sub saveExportAs()
Dim wb1, wb2 As Workbook
Dim ws As Worksheet
Dim varResult As Variant
Set wb1 = ThisWorkbook
Set ws = ThisWorkbook.Worksheets("load")
ws.Copy
Set wb2 = ActiveWorkbook
varResult = Application.GetSaveAsFilename(InitialFileName:="\\network\folder\upload_" & Format(Date, "yyyy-mm-dd") & ".csv", FileFilter:= _
"Comma Delimited / Upload Files (*.csv),*.csv", Title:="Save Upload File")
If varResult <> False Then
wb2.SaveAs Filename:=varResult, FileFormat:=xlCSV
wb2.Close Savechanges:=True
Exit Sub
End If
wb1.Activate
End Sub
Try this...
Sub exportAsCSV()
Dim wb As Workbook
Set wb = ActiveWorkbook
SaveCopyAsCSV ("Sheet1") ' replace Sheet1 with whatever sheet name you need
wb.Activate
End Sub
Private Function SaveCopyAsCSV(SourceSheet As String)
Application.DisplayAlerts = False
ThisWorkbook.Sheets(SourceSheet).copy
ActiveWorkbook.SaveAs fileName:=SourceSheet, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Function

How to export multiple selected worksheets to another workbook using VBA

I have a source excel file which contains worksheets starting with "TYPICAL" name.
I also have a code to export the "TYPICAL" worksheet to another Excel file using the Getopenfile name. As a part of code, I have to rename the source worksheet as value contained in cell "E3" and current date.
Attached code works fine for me, but I can not select multiple "TYPICAL" sheets and export. Can any one suggest a way to loop through the selected work sheets?
Sub export()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sht As Worksheet
Dim dt As String
Dim mntg As String
Set wb1 = ActiveWorkbook
Set Sht = Selection.Worksheet
Dim shtname As String
'
shtname = CStr(Sht.Name)
dt = CStr(Format(Date, "DDMMYY"))
If Left(shtname, 7) = "TYPICAL" Then
mntg = CStr(Range("E2").Value)
Sht.Name = mntg & "_" & dt
FileToOpen = Application.GetOpenFilename _
(Title:="choose a Excel file to insert selected Typical File", _
FileFilter:="*.xlsx (*.xlsx),")
'
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Sht.Name = shtname
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
End If
wb1.Activate
Sht.Copy After:=wb2.Sheets(wb2.Sheets.Count)
wb2.Save
wb2.Close
Else
MsgBox "This is not a Typical File for Export", vbExclamation, "ERROR"
End If
Sht.Name = shtname
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

VBA to Open Excel File and Paste Sheet 1 Data into “Main” Sheet in Current Workbook

Ok so I have a current workbook (Original Workbook) with one Sheet.
I would like to open an existing workbook (Data Workbook) and copy all of the contents in Sheet 1 of 'Data Workbook', then paste everything into Sheet "Main" of 'Original Workbook'.
At the end of this process I would like to close the 'Data Workbook' So far I have the following code.
however it gives me an error message
"Run-time error'1004': Cannot paste that macro formula onto a worksheet":
Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range
Set wb1 = ActiveWorkbook
Set PasteStart = [Main!A1]
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
With Sheet.UsedRange
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
End If
wb2.Close
End Sub
Hello please refer the code below and make changes according to your need. It does what you need.
Option Explicit
Sub import()
Dim filename As String
Dim curfilename As String
curfilename = ThisWorkbook.Name
filename = Application.GetOpenFilename
Application.ScreenUpdating = False
Dim x As Workbook
Set x = Workbooks.Open(filename)
With Sheets("1")
x.Sheets("1").Range("A1:Z10000").Copy '/Provide the range
End With
Dim y As Workbook
Set y = Workbooks(curfilename)
With Sheets("Main")
y.Sheets("Main").Range("A1").PasteSpecial xlPasteFormats
Application.DisplayAlerts = False
End With
x.Close SaveChanges:=False
Range("A1").Select
End Sub

VBA to Open Excel File and Paste Sheet 1 Data into "RRimport" Sheet in Current Workbook

Ok so I have a current workbook (Original Workbook) with several Sheets. I would like to open an existing workbook (Data Workbook) and copy all of the contents in Sheet 1 of 'Data Workbook', then paste everything into Sheet "RRimport" of 'Original Workbook'. At the end of this process I would like to close the 'Data Workbook' So far I have the following code, however it currently pastes a new sheet right after my sheet names "ARGimport" of my Original Workbook:
Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ActiveWorkbook
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
If Sheet.Visible = True Then
Sheet.Copy After:=wb1.Sheets("ARGimport")
End If
Next Sheet
End If
wb2.Close
End Sub
Thanks to the help of rdhs I was able to figure this out. Updated and working code below:
Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range
Set wb1 = ActiveWorkbook
Set PasteStart = [RRimport!A1]
Sheets("RRimport").Select
Cells.Select
Selection.ClearContents
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
With Sheet.UsedRange
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
End If
wb2.Close
End Sub
Does this do what you want?
Sub ImportData()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range
Set wb1 = ActiveWorkbook
Set PasteStart = [RRimport!A1]
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
For Each Sheet In wb2.Sheets
With Sheet.UsedRange
.Copy PasteStart
Set PasteStart = PasteStart.Offset(.Rows.Count)
End With
Next Sheet
End If
wb2.Close
End Sub