Vba macro subscript out of range - vba

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.

Related

Excel VBA - Close workbook

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

VBA Debug code for using a partial name match to copy and paste between active/open workbooks

I found this code in another thread here but can't get it working in my book...
What I'm trying to achieve is... The macro to be called from a wb called "SHIFT REPORT*" which looks for and switches to a wb called "PlayerTransactionReport*" to copy some data before switching back to the SHIFT REPORT and pasting it in.
The code I have is:
Sub Import_Data()
Dim wb As Workbook
Dim ShiftReport As Workbook
Dim PlayerTransactionReport As Workbook
Set ShiftReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 23) = "PlayerTransactionReport" Then Set PlayerTransactionReport = wb
Next
Sheets("Sheet1").Select
Columns("A:Z").Select
Selection.Copy
Set PlayerTransactionReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 10) = "ShiftReport" Then Set ShiftReport = wb
Next
Sheets("Data").Select
Range("A1").Select
ActiveSheet.Paste
End Sub
Currently, it's not setting the PlayerTransactionReport to the active wb but throughout the process of debugging this by myself I've had various degrees of success, but I fear that this one might have between me, Please Help!
Thanks, Stuart
You have to refer to the Parent Worksheet, whenever you are refering to Sheets() and Columns():
Sub Import_Data()
Dim wb As Workbook
Dim ShiftReport As Workbook
Dim PlayerTransactionReport As Workbook
Set ShiftReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 23) = "PlayerTransactionReport" Then Set PlayerTransactionReport = wb
Next
PlayerTransactionReport.Sheets("Sheet1").Select
Columns("A:Z").Select
Selection.Copy
Set PlayerTransactionReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 10) = "ShiftReport" Then Set ShiftReport = wb
Next
PlayerTransactionReport.Sheets("Data").Select
Range("A1").Select
ActiveSheet.Paste
End Sub
If you do not refer to the parent worksheet, then the ActiveSheet or the sheet where the code is, is the one referred.
As a next step you can improve the following 2 points:
How to avoid using Select in Excel VBA
Check whether the PlayerTransactionReport is not Nothing, before calling it:
If Not PlayerTransactionReport Is Nothing Then
PlayerTransactionReport.Sheets("Sheet1").Select
Columns("A:Z").Select
Selection.Copy
End If
Stop using Select and Activate.
Sub Import_Data()
Dim w As long
Dim PlayerTransactionReport As Workbook, ShiftReport As Workbook
Set ShiftReport = ThisWorkbook
For w = 1 to Workbooks.count
If Left(Workbooks(w).Name, 23) = "PlayerTransactionReport" Then
Set PlayerTransactionReport = Workbooks(w)
exit for
end if
Next w
if w > Workbooks.count then
debug.print "cannot find PlayerTransactionReport"
exit sub
end if
PlayerTransactionReport.workSheets("Sheet1").Columns("A:Z").Copy _
destination:=ShiftReport.workSheets("Data").Range("A1").
End Sub

How do I ensure the VBA code saves the workbook to the file path declared?

The following is my code in an attempt to delete a number of sheets in order to save a workbook with specific worksheets only:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
wb.Close
Set wb = Nothing
End Sub
The loop works fine but it refuses to save the workbook on the path I have specified.
I get this message: "Runtime error 91: Object variable or With block variable not set"
Can anyone help?
Look at your error message: Object variable or With block variable not set
It looks like you aren't able to save because you never instantiate your wb variable. Therefore wb = Nothing. You can't perform SaveAs on nothing. Try adding Set wb = ThisWorkbook below your declarations like so:
'other code
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
'other code
The wb object variable is never assigned to anything other than Nothing. But anyway you can use ThisWorkook, if you mean to save and close the workbook that contains the running code:
With ThisWorkbook
.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
.Close
End With
Thanks everyone!
It seems that I needed to set the workbook properly (Set wb = ThisWorkbook).
I also needed to change ws.name into sheetname.
This is the code that worked at the end:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & sheetname & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
'wb.Close
End Sub

Error 438 when copying data from closed workbook

every week I have to run a report, export it, manipulate it, add in the same forumulas, etc. So I figured I could probably just make a macro to do most of it for me.
I ended up creating a excel file with the forumulas so that I can just copy and paste it using VBA, however, I am getting error 438 object doesn't suppor this property or method on the line starting with wba.sheets
Here is the code.
Dim wba As Workbook
Set wba = ThisWorkbook
Application.DisplayAlerts = False
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\xxx\Documents\Custom Office Templates\xxx.xlsx")
wb.Sheets("Sheet1").Range("A1:F18").Copy
wba.Sheets("Sheet1").Range("F1").End(xlDown).Offset(2, -5).Paste
wb.Close False
Application.DisplayAlerts = True
Dim wba As Workbook
Set wba = ThisWorkbook
Application.DisplayAlerts = False
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\xxx\Documents\Custom Office Templates\xxx.xlsx")
wb.Sheets("Sheet1").Range("A1:F18").Copy
wba.Activate
Sheets("Sheet1").Range("F1").End(xlDown).Offset(2, -5).Select
Activesheet.Paste
wb.Close False
Application.DisplayAlerts = True
Using xlDown will fail if there's nothing below F1, so it's typically safer to use xlUp (as #MarcoGetrost noted)
Dim wba As Workbook, wb As Workbook
Set wba = ThisWorkbook
Application.DisplayAlerts = False
Set wb = Workbooks.Open("C:\Users\xxx\Documents\Custom Office Templates\xxx.xlsx")
wb.Sheets("Sheet1").Range("A1:F18").Copy _
wba.Sheets("Sheet1").Cells(Rows.Count,"F").End(xlUp).Offset(2, -5)
wb.Close False
Application.DisplayAlerts = True

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