Excel VBA disable opening of workbook while trying to save it - excel

I have the following macro:
Sub btnToCsv()
Dim Wb As Workbook
Dim Ds, Ws As Worksheet
Set Ds = Sheet1
Set Wb = Workbooks.Add
Set Ws = Wb.ActiveSheet
Ds.Range("A2:J200000").Copy Ws.Range("A1")
Application.DisplayAlerts = False
Wb.SaveAs ThisWorkbook.Path & "\MyCSV.csv", FileFormat:=xlCSV
MsgBox "Saved Successfully!"
Wb.Close
End Sub
The above macro gets activated from a button on an existing sheet. At the following line, a new workbook opens up on computer screen which might look a litte awkward for my non technical users. That temporary workbook closes at end of Sub.
Set Wb = Workbooks.Add
How do I disable or hide the temporary workbook from opening on screen?

Related

Get the New Workbook When Copying a Worksheet

I have several sheets I need to copy to a new workbook and then save this workbook.
I'm using the worksheet function to copy which it seems to me like it's the intended purpose of that function.
Here's the MSDN documentation on how to do this task:
Worksheets("Sheet1").Copy
With ActiveWorkbook
.SaveAs Filename:=Environ("TEMP") & "\New1.xlsx", FileFormat:=xlOpenXMLWorkbook
.Close SaveChanges:=False
End With
https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.copy
This is doing exactly what I want, but it's using the ActiveWorkbook property which might cause some error, if running other codes or just working in parallel of this code running.
I'm looking for a way to manipulate the newly created workbook without having to use the ActiveWorkbook property.
Something along the lines of this:
Dim wb as Workbook
set wb = Worksheets("Sheet1").Copy
wb.SaveAs Filename:=Environ("TEMP") & "\New1.xlsx", FileFormat:=xlOpenXMLWorkbook
wb.Close SaveChanges:=False
I've already tried this and it didn't work, but it's just to illustrate the point that it's not using the ActiveWorkbook property to refer to the new workbook.
Thanks in advance
From above comment:
Sub Tester()
With AsNewWorkbook(Sheet1)
Debug.Print .Name
.SaveAs "C:\Temp\blah.xlsx"
End With
End Sub
Function AsNewWorkbook(ws As Worksheet)
Dim wb As Workbook
Set wb = Workbooks.Add(xlWBATWorksheet) 'has one sheet...
With wb.Sheets(1) 'stolen from Cristian's answer...
If .Name = ws.Name Then .Name = .Name & "x"
End With
ws.Copy before:=wb.Worksheets(1)
Application.DisplayAlerts = False
wb.Worksheets(2).Delete
Application.DisplayAlerts = True
Set AsNewWorkbook = wb
End Function
#BigBen is right though - typically just using ActiveWorkbook is fine.
An improvement on #TimWilliams response so that you can copy multiple sheets at once:
Sub Test()
Dim sourceBook As Workbook
'
Set sourceBook = ThisWorkbook 'Or ActiveWorkbook or whatever book is needed
With CopySheetsToNewBook(sourceBook.Sheets(Array("Sheet1", "Sheet2")))
.SaveAs Filename:=Environ("TEMP") & "\New1.xlsx", FileFormat:=xlOpenXMLWorkbook
End With
sourceBook.Close SaveChanges:=False
End Sub
Public Function CopySheetsToNewBook(ByVal theSheets As Sheets) As Workbook
If theSheets Is Nothing Then
Err.Raise 91, "CopySheetsToNewBook", "Sheets not set"
End If
'
Dim newBook As Workbook
Dim tempSheet As Worksheet
'
Set newBook = Application.Workbooks.Add(xlWBATWorksheet)
Set tempSheet = newBook.Worksheets(1) 'To be deleted later
tempSheet.Name = CDbl(Now) 'Avoid name clashes with the sheets to be copied
'
theSheets.Copy Before:=tempSheet
Application.DisplayAlerts = False
tempSheet.Delete
Application.DisplayAlerts = True
'
Set CopySheetsToNewBook = newBook
End Function
Copy Worksheet(s) to a New Workbook
Sub NewWorkbook()
' Reference the source workbook.
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
swb.Worksheets("Sheet1").Copy ' copy one worksheet to a new workbook
'swb.Worksheets(Array("Sheet1", "Sheet2")).Copy ' copy multiple worksheets
' Reference the destination (new) workbook.
Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
Debug.Print swb.Name, dwb.Name
End Sub

Getting the created workbook name after copying worksheet from another workbook

How do I call and re-use the workbook that gets created after executing
ThisWorkbook.Sheets("copythis").Copy
I can't use the activeWorkbook since the user will go back to the previous workbook that has the vba.
Dim wbNew As Workbook
ThisWorkbook.Sheets("copythis").Copy
Set wbNew = ActiveWorkbook
MsgBox wbNew.Name
Even if the user goes back and selects something else, you can work with the new workbook using the wbNew object.
The newly created workbook will always be at the end of workbook array. So you can use this also
Dim wbNew
set wbNew = Application.Workbooks(Application.Workbooks.Count)
Worksheet.Copy Method
When using your line of code, the newly created workbook becomes the active one.
The Code
Option Explicit
Sub testWithVariable()
ThisWorkbook.Sheets("copythis").Copy
Dim wb As Workbook
Set wb = ActiveWorkbook
Debug.Print wb.Name
wb.Saved = True
End Sub
Sub testWithoutVariable()
ThisWorkbook.Sheets("copythis").Copy
With ActiveWorkbook
Debug.Print .Name
.Saved = True
End With
End Sub
Sub testWorksheetWithoutVariable()
ThisWorkbook.Sheets("copythis").Copy
With ActiveSheet
Debug.Print .Parent.Name ' workbook
Debug.Print .Name ' worksheet
.Parent.Saved = True
End With
End Sub

VBA. Export only visible sheet to individual workbook

Sub SaveShtsAsBook()
‘Select all visible and hide sheet’
Dim Sheet As Worksheet, SheetName$, MyFilePath$, N&
MyFilePath$ = ActiveWorkbook.Path & "\" & _
Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
' End With
On Error Resume Next '<< a folder exists
MkDir MyFilePath '<< create a folder
For N = 1 To Sheets.Count
Sheets(N).Activate
SheetName = ActiveSheet.Name
Cells.Copy
Workbooks.Add (xlWBATWorksheet)
With ActiveWorkbook
With .ActiveSheet
.Paste
.Name = SheetName
[A1].Select
End With
'save book in this folder
.SaveAs Filename:=MyFilePath _
& "\" & SheetName & ".xlsx"
.Close SaveChanges:=True
End With
.CutCopyMode = False
Next
End With
Sheet1.Activate
End Sub
I have a workbook, that contains many sheets which have visible and hide ones. I only want to export each visible sheet to individual workbook. this current code above can do the export for all the sheet in the workbook but I have to delete them 1 by 1 after that. Hope that explains my situation.
All you need to add to your code to exclude hidden sheets is a simple If..Then statement to check whether the Worksheet.Visible property is True or False.
If Not yourWorsheet.Visible Then... ... then you skip that worksheet.
The following procedure is a simpler overall approach to what you're trying to accomplish...
Export Visible worksheets to their own workbooks:
The worksheet.Copy method will create a new workbook if neither Before nor After are specified.
Sub saveVisibleSheetsAsXLSM() 'saves all visible sheets as new xlsx files
Const exportPath = "x:\yourDestinationPath\"
Dim ws As Worksheet, wbNew As Workbook
For Each ws In ThisWorkbook.Sheets 'for each worksheet
If ws.Visible Then 'if it's visible:
Debug.Print "Exporting: " & ws.Name
ws.Copy '(if no params specified, COPY creates + activates a new wb)
Set wbNew = Application.ActiveWorkbook 'get new wb object
wbNew.SaveAs exportPath & ws.Name & ".xlsm", 52 'save new wb
wbNew.Close 'close new wb
Set wbNew = Nothing 'cleanup
End If
Next ws
Set ws = Nothing 'clean up
End Sub
Worksheet.Copy Remarks:
If you don't specify either Before or After, Microsoft Excel creates a new workbook that contains the copied sheet object that contains the copied Worksheet object. The newly created workbook holds the Application.ActiveWorkbook Property (Excel) property and contains a single worksheet. The single worksheet retains the Worksheet.Name Property (Excel) and Worksheet.CodeName Property (Excel) properties of the source worksheet. If the copied worksheet held a worksheet code sheet in a VBA project, that is also carried into the new workbook.
An array selection of multiple worksheets can be copied to a new blank Workbook Object (Excel) object in a similar manner.
(Source: Documentation)

Copying from one workbook to open workbook

I am trying to copy an object from a closed workbook to the currently open workbook, the code I have bee experimenting with is:
Sub test()
Dim WB1 As Workbook
Dim WBDest As Workbook
Set WBDest = Workbooks(ActiveWorkbook.Path & "\" & ActiveWorkbook.Name)
'Open up your first workbook, copy data
Set WB1 = Workbooks.Open("path to the folder\testbook.xlsx")
WB1.Sheets("Sheet1").Range("A1:F12").Copy
'paste in second workbook
WBDest.Sheets("Sheet1").Range("A1").PasteSpecial
'Close first workbook
WB1.Close savechanges:=False
End Sub
I keep getting a "subscript out of range" error with this, if I remove the WBDest info and used activeworkbook instead, it copies the object and pastes it in the same workbook as it is the activeworkbook at the time.
Could someone please guide me on this and help me figure out what I am doing wrong.
Thanks.
As mentioned by AndyG, it should be WBDest = Workbooks.Open(..). The replacement is then:
Sub test()
Dim WB1 As Workbook
Dim WBDest As Workbook
Set WBDest = Workbooks.Open(ActiveWorkbook.Path & "\" & ActiveWorkbook.Name)
'Open up your first workbook, copy data
Set WB1 = Workbooks.Open("path to the folder\testbook.xlsx")
WB1.Sheets("Sheet1").Range("A1:A7").Copy
'paste in second workbook
WBDest.Sheets("Sheet1").Range("A1:A7").PasteSpecial
'Close first workbook
WB1.Close savechanges:=False
End Sub
Note that on the 5th line you could as easily write WBDest = ActiveWorkbook if the workbook is already open as you suggest.

Copying external Excel sheet to current workbook using VBA

I'm working on small project in which I need to add sheets to the currently open workbook from any external database of worksheets in another workbook. I made a form to import any sheet that is required in the currently open (active) workbook.
The sheets will be copied from remote (in any other folder but same computer) workbook. I am using following code but due to unknown reasons the sheets are NOT getting copied to my current workbook.
Dim wb As Workbook
Dim activeWB As Workbook
Dim FilePath As String
Dim oWS As String
Set activeWB = Application.ActiveWorkbook
FilePath = "D:\General Required Docs\DATA.xlsm"
If optFirst.Value = True Then
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
oWS = cboMaterial.Value
Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(oWS).Copy
After:=Application.ActiveWorkbook.Sheets(ThisWorkbook.Sheets.count)
activeWB.Activate
wb.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Change
wb.Worksheets(oWS).Copy
After:=Application.ActiveWorkbook.Sheets(ThisWorkbook.Sheets.count)
to
wb.Worksheets(oWS).Copy
After:=activeWB.Sheets(activeWB.Sheets.count)
assuming that oWS is the index of the worksheet you want to copy.
Sub Add_Bridge_1()
Dim wbk1 As Workbook, wbk2 As Workbook
'add your own file path
fileStr = "C:\Program Files\Microsoft Office\Office\HL DDS Templates.xlsx"
Set wbk1 = ActiveWorkbook
Set wbk2 = Workbooks.Add(fileStr)
'wbk2.Sheets("Bridge 1").Copy After:=Workbooks("WorkbookNameYouCopyCodeInto").Sheets(1)
wbk2.Sheets("Sheet Name").Copy After:=wbk1.Sheets(1)
wbk2.Saved = True
End Sub

Resources