Excel VBA - Close workbook - vba

I am importing a worksheet from another workbook to my current workbook. After I complete importing the worksheet, I want to close that other workbook. The code I am using gives the error Run-time error 9': Subscript out of range.
Sub ImportWorksheet(MyPath As String, wbName As String)
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=MyPath
Sheets(1).Copy After:=Workbooks(ControlFile).Sheets(1)
ActiveSheet.Name = wbName
Workbooks(MyPath).Close SaveChanges:=False
Windows(ControlFile).Activate
End Sub
I also tried using
Windows(MyPath).Activate
ActiveWorkbook.Close SaveChanges:=False
But I get the same error.

Since Open method of Workbooks object returns a Workbook object you can reference the opened workbook:
Sub ImportWorksheet(MyPath As String, wbName As String)
ControlFile = ActiveWorkbook.Name
With Workbooks.Open(Filename:=MyPath)
.Sheets(1).Copy After:=Workbooks(ControlFile).Sheets(1)
.Sheets(2).Name = wbName
.Close SaveChanges:=False
End With
End Sub

I like to assign variable, it removes any confusion.
Sub ImportWorksheet(MyPath As String, wbName As String)
Dim Owb As Workbook
Dim Nwb As Workbook
Set Owb = ThisWorkbook
Set Nwb = Workbooks.Open(Filename:=MyPath)
Nwb.Sheets(1).Copy after:=Owb.Sheets(1)
Owb.Sheets(2).Name = wbName
Nwb.Close False
Owb.Activate
End Sub

Workbooks(strTargetFileName).Close SaveChanges:=False

Related

Vba macro subscript out of range

Can't seem to figure out why I'm getting a run time error on the second line. Help please
Dim wb As Workbook
Set wb = Workbooks(PLC)
wb.Close SaveChanges:False
Application.DisplayAlerts=True
End sub
give this a shot
Sub test()
Dim wb As Workbook
Set wb = Workbooks("PLC.xlsx")
wb.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
When you wish to open a workbook you should use the Workbooks.Open method. Workbooks(index) only applies to workbooks that are already opened. You can check if a workbook is already open by doing e.g.
Dim wb as workbook, isOpen as boolean, myName as string
myName = "PLC"
bIsOpen = false
For each wb in Workbooks
If wb.Name = myName Then
bIsOpen = true
End if
Next wb
And use the result in your next step.

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

copying from one excel to other using VBA

I need to copy information from one excel file to other using VBA. Code makes new workbook in certain destination (*C:\Users\eliza_000\Desktop\aaa*) for whole sheet (inv) but I need only range A1:E32 in the new workbook.
Here is the code what I use to copy all sheet
Sub SaveInvWithNewName()
Dim NewFN As Variant
'Copy Invoice to a new workbook
ActiveSheet.Copy
NewFN = "C:\Users\eliza_000\Desktop\aaa\inv" & Range("E6").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
End Sub
Consider:
Sub dural()
ActiveSheet.Copy
Rows("33:1048576").Delete
Columns("F:xfd").Delete
End Sub
Adjust if you are using a version of Excel pre-2007.
Something like:
Dim WB As Workbook
Dim WB2 As Workbook
Dim NewFN As String
Set WB = ThisWorkbook
Set WB2 = Workbooks.Add(1)
WB.ActiveSheet.Range("A1:E32").Copy WB2.Sheets(1).Range("a1")
NewFN = "C:\Users\eliza_000\Desktop\aaa\inv" & Range("E6").Value & ".xlsx"
NewFN = "C:\temp\stuff.xlsx"
WB2.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
WB2.Close

Save Selected Sheets to a different work book in VBA

I would like to save a number of worksheets from the current workbook to a different workbook and exclude a sheet named "buttons" (in current one) from that saving process.
Can anybody help please? The number of worksheets is changeable FYI.
Below is what I have so far which include all the sheets from current workbook.
Sub SaveAs()
D1 = VBA.Format(Now, "mm_DD_yyyy")
For Each ws In Application.Workbooks
ws.SaveAs Filename:="C:\Users\e2309\Desktop\Andy's\GBB_Report_" & D1 & ".csv"
Next ws
Application.Quit
End Sub
Or more directly
copy the entire workbook
delete the redundant sheet
code
Sub Simpler()
Dim wb As Workbook
Dim strFile As String
strFile = "C:\temp\yourfile.xlsm"
ThisWorkbook.SaveAs strFile, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = False
ThisWorkbook.Sheets("buttons").Delete
Application.DisplayAlerts = True
End Sub
This might get you a little closer. Note this is not complete and very untested.
Sub work()
Dim WB As Workbook
Dim Nwb As Workbook
Dim WS As Worksheet
Set Nwb = New Workbook
Set WB = ThisWorkbook
For Each WS In WB.Sheets
If WS.Name <> "Don't copy" Then
WS.Copy Nwb.Sheets("sheet1")
End If
Next
Nwb.Save
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