VBA workbook out of range - subscript error - vba

I'm getting a
subscript out of range
error when im passing an array and a workbook into this function. Can anyone see what's wrong with it?
--Update--
Private Function PasteFunction(cd As Variant, wk As Workbook) As Boolean
Dim bool As Boolean, row As Integer, col As Integer
bool = False
col = 1
row = 3
Do While bool = False
MsgBox row
MsgBox col
If IsEmpty(wk.Sheets("Sheet1").Cells(row, col)) = True Then
For col = 1 To 81
wk.Sheets("Sheet1").Cells(row, col) = cd(col)
Next col
bool = True
Else
row = row + 1
End If
Loop
End Function

This line produces the error:
If IsEmpty(wk.Sheets("Sheet1").Range(col & row)) = True Then
Range (col&row) returns something like Range(1223) and excel awaits values like Range("A12:A53").
Judging on your code, the logic should be like this:
Cells(row, col) instead of Range(col & row).

subscript out of range error could be caused either due to incorrect reference to workbook or sheet reference or because your array cd is shorter than 81 items. How are you calling your function. can you post your function call. The workbook path may be incorrect also check for spelling mistakes

If cd has 81 elements then they run from cd(0) to cd(80)
If you want to put them into columns 1 to 81 you need
For col = 1 To 81
wk.Sheets("Sheet1").Cells(row, col) = cd(col-1)
Next col

Related

Application or object defined error Runtime error 1004

I have created the following code to extract information from an excel table. But I am getting an error exactly at the if statement. I have even tried executing the code from a module and even from the worksheet level. I have read about this issue and it seems that selecting the sheet seems to be the main problem, but I have also tried but in vain I can't seem to find a solution. It would be really great if someone could help me with this. Thank you in advance.
Sub test()
Dim row As Double, col As Double, inc As Double
row = 2
col = 2
inc = 20
'Sheets("sche").Range("a1").Select
For row = 2 To 15
For col = 2 To 52
If (Cells(r, c).Font.Bold Or Left(Cells(r, c).Value, 2) = "BP") Then 'Error is happening here
Sheets("sche").Cells(inc, 2).Value = Sheets("sche").Cells(r, c).Value
inc = inc + 1
GoTo zone
Else: GoTo zone
End If
zone:
Next col
Next row
End sub
You have declared row and col as variables but are using r and c in your If...Then block.
A prime example of why you should add Option Explicit at the top of every module to prevent typo's and using undeclared variables.
I've adjusted your code and tested it OK:
Note: I removed the Else condition and GoTo Zone as they were redundant in your code (at least in the example you provided). Also although not a cause of your error it's not necesarry to encapsulate your entire If...Then condition in parentheses.
Sub test()
Dim row As Double, col As Double, inc As Double
row = 2
col = 2
inc = 20
'Sheets("sche").Range("a1").Select
For row = 2 To 15
For col = 2 To 52
If Cells(row, col).Font.Bold Or Left(Cells(row, col).Value, 2) = "BP" Then 'Error is happening here
Sheets("sche").Cells(inc, 2).Value = Sheets("sche").Cells(row, col).Value
inc = inc + 1
End If
Next col
Next row
End Sub
I've changed this:
If Cells(r, c).Font.Bold Or Left(Cells(r, c).Value, 2) = "BP" Then 'Error is happening here
Sheets("sche").Cells(inc, 2).Value = Sheets("sche").Cells(r, c).Value
To this:
If Cells(row, col).Font.Bold Or Left(Cells(row, col).Value, 2) = "BP" Then 'Error is happening here
Sheets("sche").Cells(inc, 2).Value = Sheets("sche").Cells(row, col).Value
Furthermore, it's good practice to expicitly reference your objects.
This is because, for example, the implicit reference for the Cells() property is the Active Worksheet:
Using this property without an object qualifier returns a Range object that represents all the cells on the active worksheet.
This can cause unexpected results if for example, you run your code whilst a different sheet than desired is active or a user changes worksheets during the codes execution.
It would be better to write the code like:
If Sheets("sche").Cells(row, col).Font.Bold Or Left(Sheets("sche").Cells(row, col).Value, 2) = "BP" Then
The With statement can come in handy to shorten the written code when making many references to the same objects, like workbooks, worksheets and/or Ranges etc. You can read about it in the documentation.

Find the first empty cell after a text in a row

I'm working on a project and need at the moment to find the first empty cell just after text cells in a row in Excel. To clarify, let me explain to you what I'm lookng for with this screenshot
I want to write a code to return for me for like an example in the case of the 20th row the number of column of the cell E20 even if the first empty cell is A20 but like I said, i want the first empty cell juste after the last "not empty" one.
for the 21th row the result will be C21, the 22th row it will be F22 and there you go
Here's the code I wrote but for some reason it doesn't work, please help.
Function emptyCell(ws As Worksheet, ligne As Integer)
Dim m, p, n As Integer
Dim suite(700) As Integer
For k = 0 To 700
suite(k) = 0
Next
emptyCell = 0
i = 1
Do Until suite(i) = 0 And suite(i - 1) = 1
If ws.Cells(ligne, i) <> "" Then
suite(i) = 1
End If
i = i + 1
emptyCell = emptyCell + 1
Loop
End Function
Sub test()
Dim d As Integer
empty_cell = emptyCell(Sheets("tmp"), 2)
MsgBox (empty_cell)
End Sub
The logic of my code is to assign 0 for empty cells and 1 in the other caase, run a test to find the first 1-0 that's gonna appear in my array and get the column order from the order of this "1"
I know I'm not that clear cause I didnt want it to make it a long post and english is not my first language.
Thanks in advance
All if you want to get the first empty cell after the last non empty cell, why not try it like this?
Function emptyCell(ws As Worksheet, Row As Long) As Range
Set emptyCell = ws.Cells(Row, ws.Columns.Count).End(xlToLeft).Offset(, 1)
End Function
Sub Test()
Dim empty_cell As Range
Set empty_cell = emptyCell(Sheets("tmp"), 20)
MsgBox empty_cell.Address
End Sub

Runtime error 9: Subscript out of range - Pulling data from another worksheet

I'm writing a macro that pulls data from one workbook and places it into another. I think I have the code pretty much right except for an error I'm getting in one of my loops:
"Runtime error 9: Subscript out of range"
Here is the code:
Sub PullFromRunsheetsTest2()
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim file As Variant, a As String, columnItertor As Integer, path As String
path = "C:\Users\msala\Desktop\Runsheets\"
file = Dir(path & "Runsheet*")
Do Until file = "" ''looking at the first file and loops until the last one
columnIterator = 0 ''setting this as the first set of 8 numbers - will shift the next set of numbers down 8 so they don't overwrite themselves
rowIterator = 0
Do Until rowIterator = 7
a = Workbooks(file).Worksheets("Pacman Runsheet").Cells(7, (2 + rowIterator)).Value '' Set "a" = whatever value is in B7, and iterate through that row
''^^^^(THIS IS WHERE I'M GETTING THE ERROR)
ActiveSheet.Cells(5 + rowIterator + columnIterator * 8, 1).Value = a ''take that value and put it in this column, iterate through.
rowIterator = rowIterator + 1
Loop
columnIterator = columnIterator + 1 ''(ignore this for now)
file = Dir()
Loop
End Sub
From what I've read it seems like there's some sort of problem with maybe the data type of a? Not entirely sure what that might be though. Am I accidentally declaring a as an array somewhere?

How do I check whether value in active cell contains any letter or not?

For example cell "A1" is linked to cell "B1", so in formula bar for cell "A1" we have:
=B1
How can I check whether value in cell "A1" contains letter B?
I tried the following:
Dim Criteria_3 As Boolean
Dim Value As Range
Set Value = Selection
Dim x As Variant
Set x = Cells
Dim text As String
For Each x In Value
If IsNumeric(x) Then
Criteria_3 = VBA.InStr(1, x.Formula, text) > 0
As soon as value of "Text" is "" it does not work and I really struggle to fined the right solution.
your question is not really conclusive, so here are two options:
To check wheter the value contains B:
blnCheck = 0 < InStr(1, rngCell.Value, "B")
To check wheter the Formula contains B:
blnCheck = 0 < InStr(1, rngCell.Formula, "B")
Regarding your null string problem:
As soon as value of "Text" is "" it does not work and I really struggle to fined the right solution.
That's because you're using VBA.InStr(1, x.Formula, text) and in this case 1 is an invalid index on a string of length 0. You can omit that, or you can code around it like:
If Len(Trim(x.Formula)) = 0 Then
'## Do nothing
Else
Criteria_3 = VBA.InStr(1, x.Formula, text) > 0
End If
To your specific question of identifying when a value contains any alpha character(s):
You can use a function like this to test whether a value contains any letter, by evaluating the Ascii code for each character, and break when True:
Function ContainsAnyLetter(val) As Boolean
Dim ret As Boolean
Dim str$, ch$
Dim i As Long
str = LCase(CStr(val))
For i = 1 To Len(str)
ch = Mid(str, i, 1)
If 97 <= Asc(ch) And Asc(ch) <= 122 Then
ret = True
Exit For
End If
Next
ContainsAnyLetter = ret
End Function
In your code, you could call it like:
Criteria_3 = ContainsAnyLetter(x.Value) '## or x.Formula, depending on your needs
You can use LIKE
https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx
Something like if rngCell.value like "*B*" then
if your goal is to check whether the cell contains any valid range reference, then you could go like this
Option Explicit
Sub main()
Dim cell As Range
For Each cell In Worksheets("Sheet001").Range("A1:A20") '<== jus a test range, set it as per your needs
MsgBox IsCellReference(cell.Formula)
Next cell
End Sub
Function IsCellReference(text As String) As Boolean
On Error Resume Next
IsCellReference = Not Range(Replace(text, "=", "")) Is Nothing
End Function

VBA Error 1004 in function

I'm trying to write a function which returns the value of a specific cell located on the same column as the one I give in argument, (lig= row number, col=column number), but everytime I run it, I get an error '1004", here's my code:
Function week(lig As Integer, col As Integer) As Integer
Dim i As Integer
i = 0
Do Until Cells(lig - i, 1) = "Row labels"
i = i + 1
Loop
week = Cells(lig - i, col)
End Function
The line in which the error appears is :
Do Until Cells(lig - i, 1) = "Row labels"
I know that I test the values of cells containing integers before getting to this one, I suspeect a type error, but I can't fix it.
Could anyone please help ?
The error isn't a type error. The problem is that you are trying to access a cell that doesn't exist. Your loop evidently fails to reach a cell that holds the value "Row labels" and eventually tries to access Cells(0,1) -- which triggers error 1004. As to why this is happening -- you haven't provided enough details to say.
I suspect that the value in the cell is actually "Row Labels" or "ROW LABELS" or Row labels " or something else that doesn't actually match exactly. Try this:
Do Until Trim(Ucase(Cells(lig - i, 1))) = "ROW LABELS"
Or if you simply want to stop at row one use this:
Do Until lig - i = 1
i=0 will cause an error as the cells(0,1) does not exist in the sheet. You may also want an exit clause for if your logic is never found as you will get an error when you hit the end of the sheet. if you pass this lig =1 you will also get an error (as lig - i (1-1) would result in 0)so you may also want to handle that scenario
Function week(lig As Integer, col As Integer) As Integer
Dim i As Integer
i = 1'Changed to 1
Do Until Cells(lig - i, 1) = "Row labels"
i = i + 1
if i > 1000000 then exit do 'Exit clause
Loop
if i < 1000000 then
week = Cells(lig - i, col)
else
week = 0'Handle 0's in calling code
end if
End Function
You might like to consider re-writing as follows, which I think is clearer.
Function week(lig As Integer, col As Integer) As Integer
Dim i As Integer
' Thsi function will return 0 if no row with the text is found
week = 0
For i = lig To 1 Step -1
If Cells(i, 1) = "Row labels" Then
week = Cells(i, col)
Exit For
End If
Next i
End Function
' EVEN BETTER USE THIS (or similar)!
Function week(MyCell As Range) As Integer
Dim i As Integer
week = 0
For i = MyCell.Row To 1 Step -1
If MyCell.Parent.Cells(i, 1) = "Row labels" Then
week = MyCell.Parent.Cells(i, MyCell.Column)
Exit For
End If
' Note
' MyCell.Parent. returns the sheet containing the cell
' Just using Cells(i, 1) (wihtout preceeding with "MyCell.Parent." will pick up
' cells on the currently active sheet, which may not be the sheet with the cell!
'
Next i
End Function