How to export multiple selected worksheets to another workbook using VBA - 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

Related

VBA to BROWSE & COPY Data from SELECTED DCM File in Excel

As you can figure out of the topic, I am struggeling at VBA. I want to build a Code with the function:
click on a button
search the DCM file
select file
Open the document in my excel
I realised a code, but I always get a debugg "9" at this line:
ThisWorkbook.Worksheets("Tabelle1").Range("A10").PasteSpecial xlPasteValues
If you may help me I would be very happy :) thanks.
CODE
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", _
FileFilter:="DCM_Datei (*.DCM*),*dcm*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A:O").Copy
ThisWorkbook.Worksheets("Tabelle1").Range("A10").PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
try this i change structure of copy/paste method and declarate variable for main workbook and worksheet // not tested
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
dim wb as workbook, ws as worksheet
Application.ScreenUpdating = False
set wb = thisworkbook
set ws = wb.Worksheets("Tabelle1")
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="DCM_Datei (*.DCM*),*dcm*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A:O").Copy
ws.Range("A10").PasteSpecial Paste:=xlPasteValues
OpenBook.Close False
set OpenBook = nothing
End If
set wb = nothing
set ws = nothing
Application.ScreenUpdating = True
End Sub

How to copy data from csv file to other excel files

Since I am new to VBA I created a code which can open a .csv file and copy data from .csv to an excel file without opening both.
Actually it works for excel files but When I use a .csv file it displays me an error message "SUBSCRIPT OUT OF RANGE".How do I solve this? Thank You!
Sub Copywb1()
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Setwkb1 = ThisWorkbook
Setwkb2 = Workbooks.Open("C:\Desktop\AAA.xlsx")
Setwkb1 = Workbooks.Open("C\Reports\BBB.csv")
Setsht1 = wkb1.Sheets("Reports")
Setsht2 = wkb2.Sheets("Fees")
sht1.Range("A1:BM9").Copy
sht2.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True
wkb1.Close True
End Sub
Here's a working example I had that you should able to to adapt to your needs fairly easily:
Sub demo_loadDataFromCSV()
Const csvFile = "x:\mypath\myfile.csv"
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
' Application.ScreenUpdating = False 'keep these commented-out until...
' Application.DisplayAlerts = False ' ...done testing/troubleshooting!
Set ws = ThisWorkbook.ActiveSheet 'remember where we parked
Workbooks.Open csvFile 'open the csv
Set csv = ActiveWorkbook 'create object of csv workbook
cName = csv.Name 'get name of csv while its open
ActiveSheet.Columns("A:B").Copy 'copy columns A and B
ws.Activate 'go back to the first sheet
ws.Range("A1").PasteSpecial xlPasteValues 'paste values
cCount = Selection.Cells.Count 'count pasted cells
csv.Close 'close CSV
Application.DisplayAlerts = True 're-enable alerts
Application.ScreenUpdating = True 'resume screen updates
MsgBox cCount & " cells were copied from " & cName _
& " to " & ws.Parent.Name, vbInformation, "Done"
End Sub
More Information:
MS Docs : Workbooks.Open Method (Excel)
MS Docs : Range.PasteSpecial Method (Excel) (Excel)
CFO : Referring to Other Worksheets or Workbooks in Excel VBA
Code VBA : Set Workbook variable
Here are the minor changes in code, now it will select the new workbook and paste the data in the selected sheet.
Sub demo_loadDataFromCSV()
Const csvFile = "C:\Users\PC\Downloads\R1C2.txt"
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
Dim ws2 As Worksheet
' Application.ScreenUpdating = False 'keep these commented-out until...
' Application.DisplayAlerts = False ' ...done testing/troubleshooting!
Set ws = ThisWorkbook.ActiveSheet 'remember where we parked
Workbooks.Open csvFile 'open the csv
Set csv = ActiveWorkbook 'create object of csv workbook
'to open new workbook
Filename = Application.GetOpenFilename(, , "Browse for workbook")
cName = csv.Name 'get name of csv while its open
ActiveSheet.Columns("A:B").Copy 'copy columns A and B
'Open workbook
Workbooks.Open Filename
'Go to sheets Fees
Set test = ActiveWorkbook.Sheets("Fees")
test.Activate
test.Range("A1").PasteSpecial xlPasteValues 'paste values
cCount = Selection.Cells.Count 'count pasted cells
csv.Close 'close CSV
Application.DisplayAlerts = True 're-enable alerts
Application.ScreenUpdating = True 'resume screen updates
MsgBox cCount & " cells were copied from " & cName _
& " to " & ws.Parent.Name, vbInformation, "Done"
End Sub

Excel VBA- Importing specific sheets into a workbook from an external workbook

I was able to leverage someone else code to import a worksheet from an outside workbook, however the code requires me to manually change the worksheet name.
I currently have a column in workbook A that has the name of each (about 20) worksheet I am trying to pull from workbook B (which has hundreds of worksheets). Is there a way to loop this code and reference the column in workbook A to change the sheet name in my macro to be pulled from workbook B?
Code below (assuming WORKSHEET1 is the name of the worksheet I am pulling from workbook B)
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("WORKSHEET1") Then
Set wsSht = .Sheets("WORKSHEET1")
wsSht.Copy before:=sThisBk.Sheets("Sheet1")
Else
MsgBox "There is no sheet with name :WORKSHEET1 in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
Edited Try the following.
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim wbThisWB As Workbook
Dim wbTheOtherWB As Workbook
Dim vfilename As Variant
Dim WSName As String
Dim LastRow As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wbThisWB = ThisWorkbook
LastRow = wbThisWB.Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row 'get the last row whith sheets names
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbTheOtherWB = Workbooks(sFile)
With wbTheOtherWB
For i = 1 To LastRow 'rows in current workbook with worksheets names
WSName = wbThisWB.Worksheets("Sheet1").Cells(i, 1) 'where you place sheets names (here column A, from row 1 down)
If sheetExists(WSName, wbTheOtherWB) Then
Set wsSht = .Sheets(WSName)
wsSht.Copy before:=wbThisWB.Sheets("Sheet1")
Else
MsgBox "There is no sheet with name : " & WSName & " in:" & vbCr & .Name
End If
Next
wbTheOtherWB.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Function sheetExists(sheetToFind As String, wbTheOtherWB As Workbook) As Boolean
sheetExists = False
For Each Sheet In wbTheOtherWB.Worksheets
If sheetToFind = Sheet.Name Then
sheetExists = True
Exit Function
End If
Next Sheet
End Function

How to paste a worksheet copied from another workbook into an existing worksheet?

I have found a little difficult to achieve copying an existing worksheet from a workbook, let's called it, "WB_RAW" and pasting it into an existing worksheet in another workbook. So far I have the next code, which I get from another post's answer. This code copies succesfully the worksheet but it creates a new worksheet in the workbook, let's called it, "Final_WB" instead of pasting the info into an existing workbook.
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("MTM Datos") Then
Set wsSht = .Sheets("MTM Datos")
wsSht.Copy before:=sThisBk.Sheets("B012")
ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value
Else
MsgBox "There is no sheet with name :MTM Datos in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
Please help me, it's been a while since I used VBA for the last time so I do not remembe well how to use it
In this line you copy a full sheet with data
wsSht.Copy before:=sThisBk.Sheets("Bimbo12")
Change it to
wsSht.Cells.Copy sThisBk.Sheets("Bimbo12").Cells(1,1)
Application.CutCopyMode=False

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