Subscript out of range (Error 9) - excel

SourceBook = ActiveWorkbook.Name
SourceSheet = Workbooks(SourceBook).Worksheets(2).Name
If Workbooks(SourceBook).Sheets(SourceSheet).Range("B10") = "SM" Then
Workbooks(SourceBook).Worksheets(SourceSheet).Range("D11:D3000,K11:K3000,N11:AC3000,CX11:CX3000,DD11:DD3000").Select
Selection.Copy
When I type code above, I am getting result.
But later, when i type code,
ElseIf Workbooks(SourceWorkbook).Sheets(SourceSheet).Range("B1") = "Status" Then
MsgBox ("okay....")
It shows "Subscript out of range (Error 9)".
Can anybody help?

You have a typo. It should be SourceBook and not SourceWorkbook
Also this is a very complicated way of doing things. Try this instead.
Sub Sample()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook '<~~ OR ThisWorkbook?
Set ws = wb.Sheets(2)
If ws.Range("B10").Value = "SM" Then
ws.Range("D11:D3000,K11:K3000,N11:AC3000,CX11:CX3000,DD11:DD3000").Copy
ElseIf ws.Range("B1").Value = "Status" Then
MsgBox ("okay....")
End If
End Sub

Related

Range.copy problem when running excel macro from another application

I'm trying to run this code in excel from another application.The code runs without problems, however rngNumber.Copy wsData.Range("A2") isn't copied. I've tested the same code directly in excel and it was copied perfectly. I think that maybe rngNumber isn't set properly when the code is runned from another application. But, I don't get exactly the reason. Any suggestion would be appreciate, thanks.
Sub TEST()
' Try to connect to a running instance of Excel.
Dim excelApp As Excel.Application
On Error Resume Next
Set excelApp = GetObject(, "Excel.Application")
If Err Then
Err.Clear
' Couldn't connect so start Excel. It's started invisibly.
Set excelApp = CreateObject("Excel.Application")
If Err Then
MsgBox "Cannot access excel."
Exit Sub
End If
End If
' You can make it visible if you want. This is especially
' helpful when debugging.
excelApp.Visible = True
'Open the excel file (through dialog)
Dim ExcelFilePath As Variant
ExcelFilePath = excelApp.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*")
If ExcelFilePath <> False Then
Set wb = excelApp.Workbooks.Open(ExcelFilePath)
End If
' Open the excel file
Dim wb as Workbook
Set wb = excelApp.ActiveWorkbook
Dim ws as Worksheet
Set ws = wb.Worksheets(1)
ws.Activate
'Set Worksheet
Dim wsData As WorkSheet
Set wsData = wb.Worksheets(2)
'Write column titles
With wsData
.Cells(1, "A").Value = "Number"
End With
'Get column letter for each column whose first row starts with an specific string
ws.Activate
Dim sNumber as String
sNumber= Find_Column("Number")
'Define variables
Dim rngNumber As Range
' Copy and paste data from "Number" column to Column "A" in Worksheets "Data"
ws.Activate
'Find which is the last row with data in "Number" column and set range
With ws.Columns(sNumber)
Set rngNumber = Range(.Cells(2), .Cells(.Rows.Count).End(xlUp))
End With
'Copy and paste data from "Number" column
rngNumber.Copy wsData.Range("A2")
End Sub
Private Function Find_Column(Name As String) As String
Dim rngName As Range
Dim Column As String
With ws.Rows(1)
On Error Resume Next
Set rngName = .Find(Name, .Cells(.Cells.Count), xlValues, xlWhole)
' Calculate Name Column Letter.
Find_Column = Split(rngName.Address, "$")(1)
End With
End Function
Explicitly define the excel object and remove the On Error Resume Next. This works from Word.
Option Explicit
Sub TEST()
' Try to connect to a running instance of Excel.
Dim excelApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.WorkSheet, wsData As Excel.WorkSheet
Dim rngNumber As Excel.Range
On Error Resume Next
Set excelApp = GetObject(, "Excel.Application")
If Err Then
Err.Clear
' Couldn't connect so start Excel. It's started invisibly.
Set excelApp = CreateObject("Excel.Application")
If Err Then
MsgBox "Cannot access excel."
Exit Sub
End If
End If
On Error GoTo 0
' You can make it visible if you want. This is especially
' helpful when debugging.
excelApp.Visible = True
excelApp.WindowState = xlMinimized
'Open the excel file (through dialog)
Dim ExcelFilePath As Variant
ExcelFilePath = excelApp.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*")
If ExcelFilePath = False Then
MsgBox "No file not selected"
Exit Sub
End If
Set wb = excelApp.Workbooks.Open(ExcelFilePath)
Set ws = wb.Sheets(1)
Set wsData = wb.Sheets(2)
' Get column letter for each column whose first row
' starts with an specific string
Dim sNumber As String, LastRow As Long
sNumber = Find_Column(ws, "Number")
If sNumber = "#N/A" Then
MsgBox "Column 'Number' not found in " & vbLf & _
"Wb " & wb.Name & " Sht " & ws.Name, vbExclamation
Exit Sub
End If
' Copy and paste data from "Number" column to Column "A" in Worksheets "Data"
' Find which is the last row with data in "Number" column and set range
With ws
LastRow = .Cells(.Rows.Count, sNumber).End(xlUp).Row
Set rngNumber = .Cells(1, sNumber).Resize(LastRow)
End With
'Copy and paste data from "Number" column
rngNumber.Copy wsData.Range("A1")
excelApp.WindowState = xlMinimized
MsgBox LastRow & " rows copied from column " & sNumber, vbInformation
End Sub
Private Function Find_Column(ws, Name As String) As String
Dim rngName As Excel.Range
With ws.Rows(1)
Set rngName = .Find(Name, After:=.Cells(.Cells.Count), _
LookIn:=xlValues, lookat:=xlWhole)
End With
If rngName Is Nothing Then
Find_Column = "#N/A"
Else ' Calculate Name Column Letter.
Find_Column = Split(rngName.Address, "$")(1)
End If
End Function

Copy Data from one Excel Workbook to Another Workbook in Last row

I am Trying to run this Code, which will copy the Source sheet Row to Destination Sheet last Row, but my this code giving error 400 while compiling,
Advance Thanks for Help
Sub CopyData()
Dim sBook_t As String
Dim sBook_s As String
Dim sSheet_t As String
Dim sSheet_s As String
On Error GoTo Errorcatch
sBook_t = "C:\Users\Unknown\Desktop\Free\Calculators.xlsx"
Workbooks.Open (sBook_t)
sBook_s = "C:\Users\Unknown\Desktop\Free\PRODUCT_35.xlsm"
Workbooks.Open (sBook_s)
sSheet_t = "cstdatalist"
sSheet_s = "cstdata"
Sheets(sSheet_s).Range("A2").Copy Destination:=Sheets(sSheet_t).Range("A2")
End Sub
Have a try on following sub.
Sub CopyData()
Dim wb As Workbook
Dim sht, shtLocal As Worksheet
Dim rngPaste As Range
Dim rngLastData, wbPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
wbPath = "D:\dBook.xlsx"
Set wb = Workbooks.Open(wbPath)
Set sht = wb.Sheets(1)
Set shtLocal = ThisWorkbook.Sheets("Sheet1")
Set rngPaste = sht.Cells(Rows.Count, 1).End(xlUp).Offset(1) 'Destination range set after last used cell of column A
rngLastData = shtLocal.Cells(Rows.Count, "A").End(xlUp).Address
shtLocal.Range("A1:" & rngLastData).Copy rngPaste
wb.Save
wb.Close
Set sht = Nothing
Set shtLocal = Nothing
Set rngPaste = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
enter code hereHere is my adjustment of your code. What I did is declared the workbooks and the worksheets separately. This way it is clear which workbook/sheet is the source and which is the destination.
Sub CopyData()
Dim sBook_t As String
Dim sBook_s As String
Dim workbook_t As Workbook
Dim sSheet_t As Worksheet
Dim sSheet_s As Worksheet
Dim sSheet_t As String
Dim sSheet_s As String
On Error GoTo Errorcatch
sBook_t = "C:\Users\Unknown\Desktop\Free\Calculators.xlsx"
set workbook_t = Workbooks.Open (sBook_t)
sBook_s = "C:\Users\Unknown\Desktop\Free\PRODUCT_35.xlsm"
set workbook_s = Workbooks.Open (sBook_s)
set sSheet_t = workbook_t.Sheets("cstdatalist")
set sSheet_s = workbook_s.Sheets("cstdata")
sSheet_s.Range("A2").Copy Destination:=sSheet_t.Range("A2")
End Sub

How to skip runtime error 9 vba?

I make a macro to open many files and do some operations like copy and paste in final file.
But I want when there is no file to skip the piece of code connected with this file:
'create variables'
FinalFile = "order.xls"
Obj1 = "order-obj1.xls"
Obj1Range = "E11"
......
Windows(Obj1).Activate
Range(MyRange).Select
Selection.Copy
Windows(FinalFile).Activate
Range(Obj1Range).Select
ActiveSheet.Paste
Windows(Obj1).Activate
ActiveWindow.Close
Windows(Obj2).Activate
Range(MyRange).Select
Selection.Copy
Windows(FinalFile).Activate
Range(Obj2Range).Select
ActiveSheet.Paste
Windows(Obj2).Activate
ActiveWindow.Close
If I can't open some file I recieve run time error 9. So my question is how to skip the code for Obj1 and proceed to Obj2?
I hope you can understand me...
Use the commmand Dir() to check whether the file exists.
e.g.
If Dir(Obj1) <> "" Then
Windows(Obj1).Activate
Range(MyRange).Select
Selection.Copy
Windows(FinalFile).Activate
Range(Obj1Range).Select
ActiveSheet.Paste
Windows(Obj1).Activate
ActiveWindow.Close
End If
Also, you probably want to put this code into a function so as not to repeat it, but that is another question.
UNTESTED
Here is how I would do it. Without using .SELECT/.ACTIVATE
Dim destwb As Workbook
Sub Sample()
Dim FinalFile As String
Dim Obj1 As String, Obj2 As String
Dim MyRange As String, Obj1Range As String, Obj1Rang2 As String
Dim wb As Workbook
'~~> Change as applicable
FinalFile = "order.xls"
Obj1 = "order-obj1.xls"
Obj2 = "order-obj2.xls"
Obj1Range = "E11"
Obj2Range = "E12"
MyRange = "A1"
Set destwb = Workbooks(FinalFile)
On Error Resume Next
Set wb = Workbooks(Obj1)
On Error GoTo 0
If Not wb Is Nothing Then
CopyRange wb, MyRange, Obj1Range
DoEvents
Set wb = Nothing
End If
On Error Resume Next
Set wb = Workbooks(Obj2)
On Error GoTo 0
If Not wb Is Nothing Then
CopyRange wb, MyRange, Obj2Range
DoEvents
Set wb = Nothing
End If
End Sub
Sub CopyRange(w As Workbook, r1 As String, r2 As String)
On Error GoTo Whoa
Dim ws As Worksheet, rng As Range
Set ws = w.Sheets(1)
Set rng = ws.Range(r1)
r1.Copy destwb.Sheets("Sheet1").Range(r2)
DoEvents
wb.Close savechanges:=False
Exit Sub
Whoa:
MsgBox Err.Description
End Sub

Excel VBA to copy column to existing workbook

I have Workbook, source.xlsm, Worksheet "test1" Column A6:A20 that I need to copy to another WorkBook located on my C:... named dest.xlsx, Worksheet "Assets", Column "I". I need to be able to copy the data and be able to add to the column without overwriting the previous data copied. Any help would be a life saver.
Sub Align()
Dim TargetSh As String
TargetSh = "Assets"
For Each WSheet In Application.Worksheets
If WSheet.Name <> TargetSh Then
WSheet.Select
Range("A6:A20").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Sheets(TargetSh).Select
lastRow = Range("I65532").End(xlUp).Row
Cells(lastRow + 1, 1).Select
ActiveSheet.Paste
End If
Next WSheet
End Sub
Is this what you are trying? I have not tested it but I think it should work. Let me know if you get any errors.
Sub Sample_Copy()
Dim wb As Workbook, wbTemp As Workbook
Dim ws As Worksheet, wsTemp As Worksheet
Dim lastRow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("test1")
'~~> Change path as applicable
Set wbTemp = Workbooks.Open("C:\dest.xlsx")
Set wsTemp = wbTemp.Sheets("Assets")
lastRow = wsTemp.Range("I" & Rows.Count).End(xlUp).Row + 1
ws.Range("A6:A20").Copy wsTemp.Range("I" & lastRow)
Application.CutCopyMode = False
'~~> Cleanup
wbTemp.Close savechanges:=True
Set wb = Nothing: Set wbTemp = Nothing
Set ws = Nothing: Set wsTemp = Nothing
End Sub
HTH
Sid

Adding worksheets on workbook_open

I have an existing worksheet "StudentSheet1" which I need to add as many times as a user needs.
For eg, if a user enters 3 in cell "A1", saves it and closes the workbook.
I want to have three sheets: "StudentSheet1" , "StudentSheet2" and "StudentSheet3" when the workbook is opened next time.
So I will have the Code in "Workbook_Open" event. I know how to insert new sheets, but cant insert this particular sheet "StudentSheet1" three times
Here is my code:
Private Sub Workbook_Open()
Application.ScreenUpdating = False
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets.Add(Type:=xlWorksheet, After:=Worksheets(1))
Application.ScreenUpdating = True
End Sub
EDIT
Sorry I misread the question, try this:
Private Sub Workbook_Open()
Dim iLoop As Integer
Dim wbTemp As Workbook
If Not Sheet1.Range("A1").value > 0 Then Exit Sub
Application.ScreenUpdating = False
Set wbTemp = Workbooks.Open(Filename:="//Ndrive/Student/Student.xlsm")
wbTemp.Sheets("StudentSheet1").Copy After:=ThisWorkbook.Sheets(Sheets.Count)
wbTemp.Close
Set wbTemp = Nothing
With Sheet1.Range("A1")
For iLoop = 2 To .Value
Sheets("StudentSheet1").Copy After:=ThisWorkbook.Sheets(Sheets.Count)
ActiveSheet.Name = "StudentSheet" & iLoop
Next iLoop
.Value = 0
End With
Application.ScreenUpdating = True
End Sub
Why are you wanting to add sheets on the workbook open? If the user disables macros then no sheets will be added. As Tony mentioned, why not add the sheets when called by the user?
EDIT
As per #Sidd's comments, if you need to check if the sheet exists first use this function:
Function SheetExists(sName As String) As Boolean
On Error Resume Next
SheetExists = (Sheets(sName).Name = sName)
End Function
user793468, I would recommend a different approach. :)
wbTemp.Sheets("StudentSheet1").Copy After:=ThisWorkbook.Sheets(Sheets.Count)
is not reliable. Please see this link.
EDIT: The above code will fail if the workbook has defined names. Otherwise it is absolutely reliable. Thanks to Reafidy for catching that.
I just noticed OP's comment about the shared drive. Adding amended code to incorporate OP's request.
Tried and Tested
Option Explicit
Const FilePath As String = "//Ndrive/Student/Student.xlsm"
Private Sub Workbook_Open()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim TempName As String, NewName As String
Dim ShtNo As Long, i As Long
On Error GoTo Whoa
Application.ScreenUpdating = False
Set wb1 = ActiveWorkbook
Set ws1 = wb1.Sheets("Sheet1")
ShtNo = ws1.Range("A1")
If Not ShtNo > 0 Then Exit Sub
Set wb2 = Workbooks.Open(FilePath)
Set ws2 = wb2.Sheets("StudentSheet1")
For i = 1 To ShtNo
TempName = ActiveSheet.Name
NewName = "StudentSheet" & i
If Not SheetExists(NewName) Then
ws2.Copy After:=wb1.Sheets(Sheets.Count)
ActiveSheet.Name = NewName
End If
Next i
'~~> I leave this at your discretion.
ws1.Range("A1").ClearContents
LetsContinue:
Application.ScreenUpdating = True
On Error Resume Next
wb2.Close savechanges:=False
Set ws1 = Nothing
Set ws2 = Nothing
Set wb2 = Nothing
Set wb1 = Nothing
On Error GoTo 0
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
'~~> Function to check if sheet exists
Function SheetExists(wst As String) As Boolean
Dim oSheet As Worksheet
On Error Resume Next
Set oSheet = Sheets(wst)
On Error GoTo 0
If Not oSheet Is Nothing Then SheetExists = True
End Function

Resources