Runtime Erro "9" Subscript out of range - vba

so this code was made in excel 2013 and the workstations I have to use it on operate with 2003. In 2013 it works just fine, when it's in 2003 it returns "Runtime error "9" Subscript out of range". If someone could help me figure this out I would appreciate it. It appears the issue is with this bit of data
Set wsSheet = Worksheets("Sheet1")
With wsSheet
Set rnData = Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
End With"
Once again thank you for the help.
`Private Sub UserForm_Initialize()
Dim wsSheet As Worksheet
Dim rnData As Range
Dim vaData As Variant
Dim ncData As New VBA.Collection
Dim lnCount As Long
Dim vaItem As Variant
Set wsSheet = Worksheets("Sheet1")
With wsSheet
Set rnData = Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
End With
vaData = rnData.Value
On Error Resume Next
For lnCount = 1 To UBound(vaData)
ncData.Add vaData(lnCount, 1), CStr(vaData(lnCount, 1))
Next lnCount
On Error GoTo 0
With ComboBox1
.Clear
For Each vaItem In ncData
.AddItem ncData(vaItem)
Next vaItem
End With
End Sub
Private Sub CommandButton1_Click()
Dim c As Range
With Range("B2:B" & Range("B" & Rows.Count).End(xlUp).Row)
Set c = .Find(ComboBox2.Value, LookIn:=xlValues)
c.Activate
ActiveCell.EntireRow.Copy
Sheets("Sheet2").Select
RowCount = Cells(Cells.Rows.Count, "a").End(xlUp).Row
Range("a" & RowCount + 1).Select
ActiveSheet.Paste
Application.CutCopyMode = False
End With
Sheets("Sheet1").Select
Range("a1").Select
Unload Me
End Sub
Private Sub ComboBox1_Change()
Dim cell As Range
Me.ComboBox2.Clear
For Each cell In Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
If cell.Value = Me.ComboBox1 Then
Me.ComboBox2.AddItem (cell.Offset(0, 1).Value)
End If
Next cell
Me.ComboBox2.ListIndex = 0
End Sub`

Might be this typo (you are missing the dots before the two ranges):
With wsSheet
Set rnData = .Range("A2:A" & .Range("A" & Rows.Count).End(xlUp).Row)
End With
And as rory pointed out in the comments above, check if you are addressing the correct workbook. Maybe add this to be safe:
Set wsSheet = ThisWorkbook.Worksheets("Sheet1")

Related

Excel VBA automating

I'm automating excel using VBA. I have created 2 new columns and one of the columns used to have the vlookup function.Сode works properly however I faced one problem. The quantity of Countries_2018.xlsx file can be changed that is why how can I make it dynamic? I mean the data of Countries_2018.xlsx grows and shrinks. Can you check and give me idea? Thank you in advance
Sub Test() Dim Rng1 As Range Dim Rng2 As Range
Dim LastRow As Long
Columns("B:B").Insert
Cells(1, 2) = "Íàïðàâëåíèå"
Columns("S:S").Insert
Cells(1, 19) = "CDR â ìèíóòàõ"
Application.ScreenUpdating = False
Set Rng1 = Range("S2:S" & Range("A2").End(xlDown).Row)
Rng1.FormulaR1C1 = "= RC[-4] / 60"
Range("B2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-1],[Countries_2018.xlsx]Sheet!R1C[-1]:R2588C,2,0)"
Range("B2").Select
Selection.AutoFill Destination:=Range(Selection, Selection.Offset(0, -1).End(xlDown).Offset(0, 1))
Application.ScreenUpdating = True
End Sub
Try this:
Sub Test()
Dim Rng1 As Range
Dim Rng2 As Range
Columns("B:B").Insert
Cells(1, 2) = "Íàïðàâëåíèå"
Columns("S:S").Insert
Cells(1, 19) = "CDR â ìèíóòàõ"
Set Rng1 = Range("S2:S" & Range("A2").End(xlDown).Row)
Set Rng2 = Range("B2:B" & Range("A2").End(xlDown).Row)
Rng1.FormulaR1C1 = "= RC[-4] / 60"
Rng2.FormulaR1C1 = "=INDEX([Countries_2018.xlsx]Sheet!C2,MATCH(RC1,[Countries_2018.xlsx]Sheet!C1,0))"
End Sub

Filter data and copy values VBA

My code below is supposed to filter data in the wsData and then copy it into the wsTest worksheet after each other in column A. The code works except that it copies the values over each on the destination sheet rather then after each other. Any idea why?
Sub PrintReport()
Dim wbFeeReport As Workbook
Dim wsData As Worksheet
Dim wsForm As Worksheet
Dim wsTest As Worksheet
Dim FrRngCount As Range
Dim i As Integer
Dim k As Integer
Dim t As Integer
Dim s As Integer
Set wbFeeReport = Workbooks("FeExcForm.xlsm")
Set wsData = wbFeeReport.Worksheets("Data")
Set wsTest = wbFeeReport.Worksheets("Test")
wsTest.Cells.Clear
wsData.Activate
i = 1
For k = 1 To 2
With ActiveSheet
.AutoFilterMode = False
With Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, k
On Error Resume Next
.SpecialCells(xlCellTypeVisible).Copy Destination:=wsTest.Range("A" & i)
End With
i = wsTest.Range("A" & Rows.Count).End(xlUp)
.AutoFilterMode = False
End With
Next k
End Sub
As first point: if using a range with AutoFilter the copy will always exclude the hidden cells
With Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, k
.Copy wsTest.Range("A" & i)
End With
is all you need here.
Regarding your error: On Error Resume Next hides the error of i = wsTest.Range("A" & Rows.Count).End(xlUp) which would return a range rather than a numerical value.
i = wsTest.Range("A" & Rows.Count).End(xlUp).Row + 1
is your friend here :)
Everything together should look something like that:
Sub PrintReport()
Dim wbFeeReport As Workbook
Dim wsData As Worksheet
Dim wsForm As Worksheet
Dim wsTest As Worksheet
Dim FrRngCount As Range
Dim i As Integer
Dim k As Integer
Dim t As Integer
Dim s As Integer
Set wbFeeReport = Workbooks("FeExcForm.xlsm")
Set wsData = wbFeeReport.Worksheets("Data")
Set wsTest = wbFeeReport.Worksheets("Test")
wsTest.Cells.Clear
wsData.Activate
i = 1
For k = 1 To 2
With wsData
.AutoFilterMode = False
With .Range("A1", Range("A" & Rows.Count).End(xlUp))
.AutoFilter 1, k
.Copy wsTest.Range("A" & i)
End With
i = wsTest.Range("A" & Rows.Count).End(xlUp).Row + 1
.AutoFilterMode = False
End With
Next k
End Sub
EDIT: For excluding headers just change:
.Copy wsTest.Range("A" & i)
to:
If i = 1 Then .Copy wsTest.Range("A" & i) Else .Offset(1, 0).Copy wsTest.Range("A" & i)
and if you do not want any headers at all then directly use:
.Offset(1, 0).Copy wsTest.Range("A" & i)
But I havent tested it. Just tell me if you get any problems ;)

Need to change one little thing in this macro

I have this macro which does exactly what I want except for one change. I want it to sort by column "M" instead of "A". I've tried changing it manually, but I keep getting errors. I know it's probably a simple fix but I just can't seem to get it. Thanks in advance!
I've tried to change "Field:=1" to Field:="13", but I get "Run-time error '1004' AutoFilter method of range class failed".
Debug then highlights "rngFilter.AutoFilter Field:=13, Criteria1:=cell.Value"
Private Sub CommandButton1_Click()
Dim wbDest As Workbook
Dim rngFilter As Range, rngUniques As Range
Dim cell As Range
Set rngFilter = Range("A1", Range("A" & Rows.Count).End(xlUp))
Application.ScreenUpdating = False
With rngFilter
.AdvancedFilter Action:=xlFilterInPlace, Unique:=True
Set rngUniques = Range("A2", Range("A" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
ActiveSheet.ShowAllData
End With
For Each cell In rngUniques
Set wbDest = Workbooks.Add(xlWBATWorksheet)
rngFilter.AutoFilter Field:=1, Criteria1:=cell.Value
rngFilter.EntireRow.Copy
With wbDest.Sheets(1).Range("A1")
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteValuesAndNumberFormats
End With
Application.CutCopyMode = True
wbDest.Sheets(1).Name = cell.Value
wbDest.SaveAs ThisWorkbook.Path & Application.PathSeparator & _
cell.Value & " " & Format(Date, "mmm_dd_yyyy")
Next cell
rngFilter.Parent.AutoFilterMode = False
Application.ScreenUpdating = True
End Sub
Give this a try. I've updated the code so that all you need to do is change sColumn from A to whatever column letter you want:
Private Sub CommandButton1_Click()
Const sColumn As String = "A"
Dim wbDest As Workbook
Dim rngFilter As Range, rngUniques As Range
Dim cell As Range
Set rngFilter = Range(sColumn & "1", Range(sColumn & Rows.Count).End(xlUp))
Application.ScreenUpdating = False
With rngFilter
.AdvancedFilter Action:=xlFilterInPlace, Unique:=True
Set rngUniques = Range(sColumn & "2", Range(sColumn & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0
End With
For Each cell In rngUniques
Set wbDest = Workbooks.Add(xlWBATWorksheet)
rngFilter.AutoFilter Field:=1, Criteria1:=cell.Value
rngFilter.EntireRow.Copy
With wbDest.Sheets(1).Range("A1")
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteValuesAndNumberFormats
End With
Application.CutCopyMode = True
wbDest.Sheets(1).Name = cell.Value
Application.DisplayAlerts = False
wbDest.SaveAs ThisWorkbook.Path & Application.PathSeparator & cell.Value & " " & Format(Date, "mmm_dd_yyyy")
wbDest.Close False
Application.DisplayAlerts = True
Next cell
rngFilter.Parent.AutoFilterMode = False
Application.ScreenUpdating = True
End Sub
Try substituting this where your debug error is:
ActiveSheet.Range("A1").CurrentRegion.AutoFilter Field:=13, Criteria1:=cell.Value
Basically, it seemed that your rngFilter variable was restricting your range to Column A and you're trying to filter based on a column that's outside of this range.
Let me know if it works!

Excel VBA delete entire row if both columns B and C are blank

I'm trying to delete an entire row in excel if column B and C are blank for that row. I have this vba code that deletes an entire row if the whole row is blank. How can I only delete the row if B and C have no value?
Thank you
Sub DeleteBlank()
Dim rng
Dim Lastrow As Integer
Set rng = Nothing
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
For Each i In Range("B1:B" & Lastrow)
If Application.CountA(i.EntireRow) = 0 Then
If rng Is Nothing Then
Set rng = i
Else
Set rng = Union(rng, i)
End If
End If
Next i
MsgBox (Lastrow)
If Not rng Is Nothing Then
rng.EntireRow.Delete
End If
End Sub
--Update--
The problem is solved. Thanks to izzymo and sous2817
Here is the current code
Sub DeleteBlank()
Dim i As Integer
Dim Lastrow As Integer
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
MsgBox (Lastrow)
For i = Lastrow To 2 Step -1
If Trim(Range("B" & i).Value) = "" And Trim(Range("C" & i).Value) = "" Then
Range("B" & i).EntireRow.Select
Selection.Delete
End If
Next i
MsgBox "Done"
End Sub
As asked for, here is a way to do it without looping:
Sub NoLoopDelete()
Dim lr As Long
lr = Range("A" & Rows.Count).End(xlUp).Row
With Sheet1.Range("A1:I" & lr)
.AutoFilter
.AutoFilter Field:=2, Criteria1:="="
.AutoFilter Field:=3, Criteria1:="="
.Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
.AutoFilter
End With
End Sub
The results should be the same, but this way should be faster, especially if you have a lot of rows. Obviously, change the column reference to suit your layout and feel free to fancy it up w/ some error checking,etc.
Try this
Sub DeleteBlank()
Dim i as Integer
Dim Lastrow As Integer
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To Lastrow
If Trim(Range("B" & i).Value) = "" And Trim(Range("CB" & i).Value) = "" Then
Range("B" & i).EntireRow.Select
Selection.Delete
i = i - 1
End If
Next i
MsgBox "Done"
End Sub

VBA Excel AutoFilter Error

I am getting following error when trying to auto filter in vba:
The object invoked has disconnected from its clients.
So what i am trying to do is auto filter, search for empty spaces and delete the rows. Can anyone please help?
I have tried the standard solutions provided online e.g. option explicit etc but to no avail.
Data:
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lngLastRow As Long
Dim lngLastRowD As Long
Application.ScreenUpdating = False
'Concatenate the Row A and B
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
Worksheets(1).Range("D2:D" & lngLastRow).Value = Evaluate("=A2:A" & lngLastRow & "&""""&" & "B2:B" & lngLastRow)
lngLastRowD = Worksheets(1).Cells(Rows.Count, "D").End(xlUp).Row
Set ws = Worksheets(1)
Set Rng = Worksheets(1).Range("A2:A" & lngLastRowD)
With Rng
.AutoFilter field:=1, Criteria1:=""
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
ws.AutoFilterMode = False
Application.ScreenUpdating = True
ThisWorkbook.Sheets(1).Range("A2").Select
End Sub
Since Worksheets() want the name of the sheet, like "Sheet1", use sheets(1).
Why are you creating the variable ws and rng when you only use them once
I ran this and it deleted rows with no data in column A.
Private Sub Worksheet_Change()
Dim lngLastRow As Long
Dim lngLastRowD As Long
Application.ScreenUpdating = False
'Concatenate the Row A and B
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
sheets(1).Range("D2:D" & lngLastRow).Value = Evaluate("=A2:A" & lngLastRow & "&""""&" & "B2:B" & lngLastRow)
lngLastRowD = Worksheets(1).Cells(Rows.Count, "D").End(xlUp).Row
With sheets(1).Range("A2:A" & lngLastRowD)
.AutoFilter field:=1, Criteria1:=""
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
sheets(1).AutoFilterMode = False
Application.ScreenUpdating = True
Sheets(1).Range("A2").Select
End Sub
In the end i restored in approaching the issue from another angle:
Dim i As Integer, counter As Integer
i = 2
For counter = 1 To lngLastRowD
If Worksheets(1).Range("A2:A" & lngLastRowD).Cells(i) = "" And Worksheets(1).Range("D2:D" & lngLastRowD).Cells(i) <> "" Then
Worksheets(1).Range("A2:A" & lngLastRowD).Range("A" & i & ":D" & lngLastRowD).Select
Selection.Delete
GoTo TheEND
Else
i = i + 1
Debug.Print "i is " & i
End If
Next