Merge content of two Excel file using VB macro Code - vba

how to merge content of two Excel file using VB macro Code .
Sub GetSheets()
Dim temp As String
Path = "C:\Users\....\ Desktop\Excel combine\"
Filename = Dir(Path & "*.xlsx")
Do While Filename "" Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
temp = ActiveWorkbook.Name ActiveSheet.Name = temp
ActiveWorkbook.Sheets(temp).Copy After:=ThisWorkbook.Sheets(1)
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
The code what i am getting online is not meeting the requirement.

Below Code will Copys Entire Sheet1 of WorkBook1 and places to WorkBook2 after Sheet1
Sub CopySheet_From_WB1_To_WB2()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb1 = Application.Workbooks.Open("C:\Users\...\Desktop\1.xlsx")
Set ws1 = wb1.Sheets("sheet1") 'replece 'Sheet1' with your sheet name
Set wb2 = Application.Workbooks.Open("C:\Users\...\Desktop\2.xlsx")
'Copying WorkBook1's Sheet1 to Workbook2 after Sheet1
ws1.Copy After:=wb2.Sheets("Sheet1") 'replece 'Sheet1' with your sheet name
wb1.Save
wb1.Close
wb2.Save
wb2.Close
End Sub
Below Code will copy used cells values from Sheet1 of Workbook1 and paste after last used row of Sheet1 of Workbook2
Sub CopySheet1Data_to_Sheet2()
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb1 = Application.Workbooks.Open("C:\Users\...\Desktop\1.xlsx")
Set ws1 = wb1.Sheets("sheet1") 'replece 'Sheet1' with your sheet name
ws1.Range(Cells(1, 1), ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Set wb2 = Application.Workbooks.Open("C:\Users\..\Desktop\2.xlsx")
Set ws2 = wb2.Sheets("Sheet1")
ws2.Activate
lastUsedRow = ActiveCell.SpecialCells(xlLastCell).Row
ws2.Cells(lastUsedRow + 1, 1).Select
ActiveSheet.Paste
wb1.Save
wb1.Close
wb2.Save
wb2.Close
End Sub

Related

Excel VBA - Copying all Worksheets from a specific workbook into an active workbok

I'm trying to copy all worksheets from a file saved on a network drive into my current active workbook. After they are copied I would like to hide them.
The tricky part, which I have yet to been able to find, is every time the macro is re-run I would like those worksheets that were previously copied over to be overwritten or deleted and replaced by the new worksheets from the existing file I am copying from.
Currently, I have my code set up to just copy over a specific worksheet depending on the string of a hyperlink. Below is what I've started but its not quite the direction I want to head.
Note the below is the edited script:
Sub ImportWorksheets()
Dim wb As Workbook, ws As Worksheet, wbTarget As Workbook, wsTarget As Worksheet
Application.ScreenUpdating = False
Dim pth As String
pth = wb.Path
Dim titleDetailPth As String
titleDetailPth = Left(pth, InStrRev(pth, "\") - 1)
Dim filePthName As String
filePthName = titleDetailPth & "\New Release Templates\" & "Key New Release Accounts Details.xlsx"
Set wb = ActiveWorkbook 'Your workbook
Set wbTarget = Workbooks.Open(filePthName, UpdateLinks:=False, ReadOnly:=True) 'The drive workbook
For Each wsTarget In wbTarget.Worksheets 'a loop for each worksheet on the drive workbook
For Each ws In wb.Worksheets ' a loop for each worksheet on your workbook
If wsTarget.Name = ws.Name Then 'if the sheet you are trying to import exist, it will delete it
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wsTarget.Copy After:=wb.Sheets(wb.Sheets.Count) 'this will copy it into the last sheet
wb.Sheets(wb.Sheets.Count).Visible = 0 'this will hide it
Next wsTarget
wbTarget.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub
Then this should do the work for you:
Sub ImportWorksheets()
Dim wb As Workbook, ws As Worksheet, wbTarget As Workbook, wsTarget As Worksheet
Application.ScreenUpdating = False
Set wb = ThisWorkbook 'Your workbook
Set wbTarget = Workbooks.Open("wherever your drive file is", UpdateLinks:=False, ReadOnly:=True) 'The drive workbook
For Each wsTarget In wbTarget.Worksheets 'a loop for each worksheet on the drive workbook
For Each ws In wb.Worksheets ' a loop for each worksheet on your workbook
If wsTarget.Name = ws.Name Then 'if the sheet you are trying to import exist, it will delete it
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wsTarget.Copy After:=wb.Sheets(wb.Sheets.Count) 'this will copy it into the last sheet
wb.Sheets(wb.Sheets.Count).Visible = 0 'this will hide it
Next wsTarget
wbTarget.Close SaveChanges:=False
Application.ScreenUpdating = True
End Sub

open a workbook from network drive and paste the data in existing workbook

I have two workbook. WB1, is my active workbook from network folder itself, and WB2 is the workbook that is already available in the network drive.
I wanted to open WB2, copy all the contents and paste In WB1 and close WB2 without saving.
Additionally, I am trying to delete in column 8 of WB1 all those that does not contain "TRU".
I tried the below code , But I am not sure how I could specify the get to open for my Network drive.
here is my code.
Sub newWB()
Dim WB1 As workbook
Dim WB2 As workbook
Dim i As Long, j As Long
Dim totalrows As Long
Dim PasteToStart As Range
Dim FileToOpen
Dim sheet As Worksheet
Set WB1 = ActiveWorkbook
Set PasteToStart = [Sheet1!A1]
FileToOpen = Application.GetOpenFilename("file://cw.wan.com/root/Loc/PL/04/Projektlist.xlsx")
If FileToOpen = False Then
MsgBox ("no File Found")
Exit Sub
Else
Set WB2 = Workbooks.Open(Filename:=FileToOpen)
For Each sheet In WB2.Sheets
With sheet.UsedRange
.Copy PasteToStart
Set PasteToStart = PasteToStart.Offset(.Rows.Count)
End With
Next sheet
End If
With ActiveWorkbook.Sheets("Sheet1")
totalrows = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = totalrows To 2 Step -1
If .Cells(i, 8).Value <> "TRU" Then
Cells(i, 8).EntireRow.Delete
End If
Next
End With
WB2.Close
End Sub

Combine Worksheets Into New Workbook Based on Criteria and Save

I have a workbook made up with 100+ worksheets. These worksheets have account number/names/days in the name of the worksheet.
The naming convention for the worksheets follows this pattern of AccountNumber/AccountName/Description:
11-Greg-Monday
11-Greg-Tuesday
11-Greg-Friday
38-Rachel-Sunday
38-Rachel-Tuesday
38-Rachel-Saturday
I would like Excel to loop through all the worksheets, and extract all of the 11-Greg worksheets and save into a new workbook named 11-Greg, and then do the same for 38-Rachel, etc. I have a list of the account numbers/names on a worksheet named "Accounts" in the workbook.
Would it be possible to maintain the formulas after the extract of the worksheets, and formatting like column widths?
I found this code that might work to start, but I don't know how to reference the list on the "Accounts" tab to loop through for the account names?
Dim wb as Workbook, sht as WorkSheet
Dim strFileName As String
'Copy sheet as a new workbook
ActiveWorkbook.Sheets("Sheet1").Copy
Set wb = ActiveWorkbook
Set sht = wb.Sheets(1)
'SaveAs
strFileName = Application.GetSaveAsFilename(wb.Name) & "xlsx"
If strFileName = "False" Then Exit Sub 'User Canceled
wb.SaveAs Filename:=strFileName
The easiest way would be to create a list of the names you want to stack on a separate list. set that list as a range and then loop through each cell checking to see if the x letters of the sheet name match. something like this
Sub stacksheets()
Dim rng As Range, cCell As Range
Dim ws As Worksheet
Dim wb As Workbook, wb2 As Workbook
Dim shName As String
Set rng = ActiveWorkbook.Sheets("list").Range("a1:a2") ''this would be the list of names
Set wb2 = ActiveWorkbook ''remembering activeworkbook so can return
For Each cCell In rng
shName = Left(cCell.Value, 5) ''this needs to be the minimum letters from each name that is unique
Set wb = Workbooks.Add
For Each ws In wb2.Sheets
If InStr(ws.Name, shName) > 0 Then ''checks for name in sheet name
ws.Copy after:=wb.Sheets(1)
wb2.Activate
End If
Next ws
wb.SaveAs (wb2.Path & "\" & cCell.Value) '' saves workbook as list name
Next cCell
End Sub

value paste a loop through file vba

Good day, I have about 125 spreadsheets in a folder and want to consolidate all the data, that I put onto one sheet for each file, from all the spreadsheets onto a different workbook. I have a loop through files in folder but it pastes the formula and not the actual values. How could I do this with the below code? I have searched through the site and anything that looks like it could work causes an error. Any help with this would be much appreciated.
Sub LoopThroughFilesInFolder()
Dim mainwb As Workbook
Dim wb As Workbook
Dim i As Integer
Set mainwb = ThisWorkbook
mainwb.Activate
Sheets("Engine").Select
Range("a2:c500").ClearComments
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")
Set FolderObj = FileSystemObj.GetFolder("C:\Desktop\Vessel folder 2016") 'Use path of the folder
For Each fileobj In FolderObj.Files 'loop through the files
If fileobj.Name <> "Bronco.xlsm" And fileobj.Name <> "~$Bronco.xlsm" And (FileSystemObj.GetExtensionName(fileobj.Path) = "xlsx" Or FileSystemObj.GetExtensionName(fileobj.Path) = "xlsm") Then
Application.DisplayAlerts = False
Set wb = Workbooks.Open(fileobj.Path)
'copy the results from the just opened wb
wb.Worksheets("ZenGarden").Select
lastcell = Range("a2:EQ5").SpecialCells(xlCellTypeLastCell).Address
Range("a2:" & lastcell).Select
Selection.Copy
'go to the mainworkbook and paste data
mainwb.Activate
Sheets("Engine").Select
If Range("a2").Value = "" Then
Range("a2").Select
Else
Range("a1").End(xlDown).Offset(1, 0).Select
End If
ActiveSheet.Paste
wb.Activate
wb.Save
wb.Close
mainwb.Activate
End If
Next fileobj
End Sub
Use Range.PasteSpecial xlPasteValues, for example:
'Copy the range into Clipboard
wb.Sheets(1).Range("A4").CurrentRegion.Copy
'Setup target range to paste Clipboard values
Dim targetRange As Range
Set targetRange = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Offset(1, 0)
'Paste Values into target range
targetRange.PasteSpecial xlPasteValues
So in your case it would look something like:
'copy the results from the just opened wb
wb.Worksheets("ZenGarden").Select
lastcell = Range("a2:EQ5").SpecialCells(xlCellTypeLastCell).Address
Range("a2:" & lastcell).Select
Selection.Copy
'go to the mainworkbook and paste data
mainwb.Activate
Dim targetSheet as Sheet
Set targetSheet = Sheets("Engine")
Dim targetRange As Range
Set targetRange = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Offset(1, 0)
'Paste Values into target range
targetRange.PasteSpecial xlPasteValues

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