Move Sheet to a Visible Excel Instance - vba

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

Related

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

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

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