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

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

Related

Excel VBA Check if worksheet exists before copy worksheet to workbook a

I'm trying develop a macro that pulls in all sheets from all workbooks in a folder if that worksheet doesn't already exist in the master workbook.
IE
Folder
|---Summary Sheet.xlsm
|---Sheet 1 date1.xlsx
|---Sheet 2 date2.xlsx
etc.
The macro opens the workbook, renames the sheet to the date off a cell, copies it across then closes it without saving/prompting. I can't seem to incorporate the name check correctly. I've looked over
Test or check if sheet exists
Excel VBA If WorkSheet("wsName") Exists
But lack the experience to properly translate the concepts across.
This is the code so far. Running now throws a runtime error 438 with
sheetToFind = ThisWorkbook.Sheets(1)
Sub ConslidateWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Dim sheetToFind As String
Dim sheetExists As Boolean
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = Environ("userprofile") & "\Folder\"
Filename = Dir(FolderPath & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
sheetExists = False
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Name = Sheet.Range("C4")
sheetToFind = ThisWorkbook.Sheets(1)
If sheetToFind = Sheet.Name Then
sheetExists = True
End If
If sheetExists = False Then
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Workbooks(Filename).Close False
Filename = Dir()
End If
Next Sheet
Loop
Application.ScreenUpdating = True
End Sub
The problem I faced with the answers above were that they didn't check each sheet each time. I found another function from
Excel VBA If WorkSheet("wsName") Exists
Using that I was able to make everything work.
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each Sheet In ThisWorkbook.Worksheets
If sheetToFind = Sheet.Name Then
sheetExists = True
Exit Function
End If
Next Sheet
End Function
Sub ConslidateWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
FolderPath = Environ("userprofile") & "\Folder\"
Filename = Dir(FolderPath & "*.xlsx")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Name = Sheet.Range("C4")
result = sheetExists(Sheet.Name)
Debug.Print result
If result = True Then
Workbooks(Filename).Close False
Filename = Dir()
End If
If result = False Then
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Workbooks(Filename).Close False
Filename = Dir()
End If
Next Sheet
Loop
Application.ScreenUpdating = True
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

Prevent workbook from switching to newly imported sheet

I have a work book that import a sheet through a control button. Currently the workbook is switching to the newly imported sheet and I would like to prevent that from happening, so that is stays on the sheet with the control button.
Here is my code:
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(sWSName) Then
Set wsSht = .Sheets(sWSName)
wsSht.Copy after:=sThisBk.Sheets("Sheet3")
Else
MsgBox "There is no sheet with name :Raw_Data 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 Boolean
Dim ws As Worksheet
On Error Resume Next
sWSName = InputBox("Enter sheet name")
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
I could not work out where in the code it is switching, perhaps I need to put some code in to make it remain static on the import?
Thanks in advance
Add this to your declare block
Dim sThisSht As Worksheet
And this where you also set the sThisBk
Set sThisSht = ActiveWorksheet
And then before you revert ScreenUpdating = True, add this to return to the active sheet set at the start:
sThisSht.Activate

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

Move Sheet to a Visible Excel Instance

I have created a userform in a workbook. When the workbook is opened this is the code that is run:
Private Sub Workbook_Open()
Application.Visible = False
UserForm1.Show
End Sub
So now the user is only seeing the Userform. There is a button on the UserForm that creates a sheet in the invisible running workbook, and MY MAIN OBJECTIVE:
(1) Open a new instance of Excel
(2) Set the new instance of Excel as Visible (Application.Visible = True)
(3) Move the sheet from the invisible instance to the new created visible one.
This is the code I tried running without success:
Sub Move()
' Check if there is a sheet named "Data Sheet"
For Each s In ThisWorkbook.Sheets
If Not s.Name <> "Data Sheet" Then
' if true then create new excel instance
Dim oXLApp As Object, wb As Object
Dim ws As Worksheet
Set oXLApp = CreateObject("Excel.Application")
oXLApp.Visible = True
Set wb = oXLApp.Workbooks.Add
'move the sheet "Data Sheet" to new workbook
s.Move Before:=wb.Sheets(1)
'delete all sheets in new workbook except "Data Sheet"
Application.DisplayAlerts = False
With wb
For Each ws In Worksheets
If ws.Name <> "Data Sheet" Then ws.Delete
Next
End With
Application.DisplayAlerts = True
End If
Next s
End Sub
I managed to move the sheet to a new workbook but within the same invisible excel instance using the below code:
Sub Move2()
Dim newWb As Workbook
Dim ws As Worksheet
For Each s In ThisWorkbook.Sheets
If Not s.Name <> "To Do" Then
Dim sheetName As String
sheetName = s.Name
Set newWb = Workbooks.Add
s.Move Before:=newWb.Sheets(1)
Application.DisplayAlerts = False
With newWb
For Each ws In Worksheets
If ws.Name <> "To Do" Then ws.Delete
Next
End With
Application.DisplayAlerts = True
End If
Next s
End Sub
What is my mistake and what is a good workaround?
As mentioned in the comments above, you cannot move a worksheet to a different instance of Excel. Here is one workaround.
We will use the .SaveCopyAs method to save a copy of the existing workbook. You can read more about .SaveCopyAs HERE
Logic
Save a copy of the existing workbook using .SaveCopyAs in user's temp directory.
Open the copy in a new instance of excel and delete unwanted sheets.
<Optional Step> Re-Save the file (If required) at a new location as .xlsx to remove all macros.
Code (TRIED AND TESTED)
Option Explicit
Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Const MAX_PATH As Long = 260
Dim TempFile As String
Sub MoveSheet()
Dim oXLApp As Object, wb As Object, ws As Object
TempFile = TempPath & "MyFile.xlsm"
On Error Resume Next
Kill TempFile
On Error GoTo 0
ThisWorkbook.SaveCopyAs TempFile
Set oXLApp = CreateObject("Excel.Application")
Set wb = oXLApp.Workbooks.Open(TempFile)
oXLApp.DisplayAlerts = False
For Each ws In wb.Worksheets
If ws.Name <> "Data Sheet" Then ws.Delete
Next
'~~> Optional step to re save the file as xlsx
wb.SaveAs "C:\MyNewFile.xlsx", 51
oXLApp.DisplayAlerts = True
oXLApp.Visible = True
End Sub
'~~> Function to get the user's temp directory
Function TempPath() As String
TempPath = String$(MAX_PATH, Chr$(0))
GetTempPath MAX_PATH, TempPath
TempPath = Replace(TempPath, Chr$(0), "")
End Function