Count Rows Until Finding Specific String - vba

I am trying to use Excel VBA to count the number of rows until I hit a specific string and set a variable equal to it.
Something like:
Dim i as Integer
i = Worksheets("Scope Phase Document").Range("A1", Range("A1").End(xlDown)).Find("FACTS - What are we measuring?").Count
I know this isn't the correct syntax and I'm probably missing other stuff, but just using the different functions I currently know, this is what I would hope would do the trick. I get
Run-time error '91' saying "Object variable or With block variable not
set
I have tried a few different ways of doing it, but can't figure out a way that doesn't result in an error.
So I want to start at A1 and count all the rows down until I reach the specific string "FACTS - What are we measuring?".
Any help would be greatly appreciated!

I prefer MATCH, but if the match is not found it throws an error. So we need to test for that:
Dim i As Long
i = 0
On Error Resume Next
i = Application.WorksheetFunction.Match("FACTS - What are we measuring?", ActiveSheet.Range("A:A"), 0)
On Error GoTo 0
If i > 0 Then
' do you stuff with i
End If

So you basically want MATCH():
=MATCH("FACTS - What are we measuring?",A:A,0)
It returns the row number of matched string.

Your code is fine except you should use the Row property. The Count property as you have used it will return 1 because the Find method returns one cell (the first cell where a match is found).
Dim i as Integer
i = Worksheets("Scope Phase Document").Range("A1", Range("A1").End(xlDown)).Find("FACTS - What are we measuring?").Row
Like Scott mentioned, if your text is not found, Excel will throw an error.

I'd do this:
Sub rowcounter()
Dim i As Integer
Range("A1").Select
i = 0
Do
Selection.Offset(1, 0).Select
i = i + 1
Loop Until Selection.Value = "FACTS - What are we measuring?"
MsgBox "rows count is " & i
End Sub

Related

Excel VBA Nested For Loop Returns Run Time Error 9

After the 12th found match of the loop, I have a Run-time Error 9 on the rptVals array. Basically, the rptcount hits 247 - where rptRows has a count of 246. I have tried doubling and quadrupling the size of rptRows, and each time I pass the 12th match I get the error. I tried loading a different data set that has one more row of data than the first workbook, and I get the error there after the 13th match - again regardless of rptRows count size, but always matching report counts maximum count.
Any ideas why this is happening? Also, I'm a chemist, not a programmer, so sorry if this isn't the prettiest code or the most efficient or whatever. If it works, I'm happy. Also, I've been made aware of Dictionaries, but I have a better grasp on arrays and loops than I do dictionaries (which obviosly isn't saying much, but oh well).
Sub PrntFllEle()
With Workbooks("Full Element Analysis Current").Worksheets("All _
Samples")
rptRows = Range("H6:IS6").Columns.Count 'here is the start of the
'problem. rptRows = 246
'rptrng = rptRows * 2 I made this variable to double/quadruple the _
size of rptRows count
rptVals = .Range("H6:IS6" & rptRows).Value
End With
With Workbooks(FlNm).Worksheets("Report")
'rEleAn, seen below the range of data captured in a separate sub.
'This will also have an associated array ElAr from the other sub.
chkRows = rEleAn.Rows.Count
End With
For rptcount = LBound(rptVals) To UBound(rptVals)
For chkcount = LBound(ElAr) To UBound(ElAr)
If rptVals(1, rptcount) <> "" Then 'I had to include this as _
I have some blank cells _
in array and this was the _
quickest way to deal with it.
'This next line is where the run-time error occurs. rptVals = _
Subscript out of Range and rptcount = 247
'Note, the UBound(rptVals) is 6241.
If rptVals(1, rptcount) = Mid((ElAr(chkcount, 1)), 1, 2) Then
MsgBox rptVals(1, rptcount)
'MsgBox just a place holder for now.
End If
Else
Exit For
End If
Next
Next
End Sub
All variables are global, btw. I've check those values, and everything that could affect this is Long. All arrays are Variants as I have strings and numbers to deal with. Ranges are appropriately Dim As Range.
Your For ... Next construction is defaulting to the first rank of your array. You want the second rank.
For rptcount = LBound(rptVals, 2) To UBound(rptVals, 2)
For chkcount = LBound(ElAr, 1) To UBound(ElAr, 1)

Type Mismatch that is normally matched [duplicate]

In some of my column's cells there appear #VALUE! words and formulas inside are as follows example:
=IF(VALUE(RIGHT(CELL("nome.arquivo";A1);LEN(CELL("nome.arquivo";A1))-SEARCH("]";CELL("nome.arquivo";A1))))=1;1;1+INDIRECT(ADDRESS(329;COLUMN();;;VALUE(RIGHT(CELL("nome.arquivo";A1);LEN(CELL("nome.arquivo";A1))-SEARCH("]";CELL("nome.arquivo";A1))))-1)))
Mentioned column is CT. Now when i am trying to loop through the cells when it comes to first occurence of #VALUE! i get an error:
Run Time Error 13, Type mismatch on this line:
L = 9
Do While Cells(L, "CT").Value <> "" '<========= HERE AN ERROR
L = L + 8
Loop
How to fix that?
Cells doesn't take any String parameter, the type mismatch error you're getting has nothing to do with #VALUE / the data being processed - because the code never gets to evaluate the data, since Cells wants two Integer parameters: dang this bites me everytime - apparently you can use string parameters in the Cells function. Ugh.
So the problem is with comparing the value to "" - a string. #VALUE! isn't a valid string function so you need to account for it:
Dim theCell As Range
Set theCell = Cells(L, "CT")
If Not IsError(theCell.Value) Then
Do While Not IsEmpty(theCell.Value)
'...
L = L + 8
Loop
End If
You might also want to correctly qualify that function call:
Do While Not IsEmpty(ActiveSheet.Cells(L, "CT").Value)
That way it's explicit that you're looking at a cell in the active worksheet; an unqualified call is implicitly doing that, and anything implicit is potentially confusing and bug-prone.
Make sure the top of the module says Option Explicit and that L is properly declared:
Dim L As Long
"L" being a meaningless identifier, you should consider naming it after what you're using it for:
Dim currentRow As Long
currentRow = 9
Do While Not IsEmpty(ActiveSheet.Cells(currentRow, "CT"))
That way your code becomes much easier to read, follow and understand.

VBA Run Time Error 13 Type Mismatch #VALUE

In some of my column's cells there appear #VALUE! words and formulas inside are as follows example:
=IF(VALUE(RIGHT(CELL("nome.arquivo";A1);LEN(CELL("nome.arquivo";A1))-SEARCH("]";CELL("nome.arquivo";A1))))=1;1;1+INDIRECT(ADDRESS(329;COLUMN();;;VALUE(RIGHT(CELL("nome.arquivo";A1);LEN(CELL("nome.arquivo";A1))-SEARCH("]";CELL("nome.arquivo";A1))))-1)))
Mentioned column is CT. Now when i am trying to loop through the cells when it comes to first occurence of #VALUE! i get an error:
Run Time Error 13, Type mismatch on this line:
L = 9
Do While Cells(L, "CT").Value <> "" '<========= HERE AN ERROR
L = L + 8
Loop
How to fix that?
Cells doesn't take any String parameter, the type mismatch error you're getting has nothing to do with #VALUE / the data being processed - because the code never gets to evaluate the data, since Cells wants two Integer parameters: dang this bites me everytime - apparently you can use string parameters in the Cells function. Ugh.
So the problem is with comparing the value to "" - a string. #VALUE! isn't a valid string function so you need to account for it:
Dim theCell As Range
Set theCell = Cells(L, "CT")
If Not IsError(theCell.Value) Then
Do While Not IsEmpty(theCell.Value)
'...
L = L + 8
Loop
End If
You might also want to correctly qualify that function call:
Do While Not IsEmpty(ActiveSheet.Cells(L, "CT").Value)
That way it's explicit that you're looking at a cell in the active worksheet; an unqualified call is implicitly doing that, and anything implicit is potentially confusing and bug-prone.
Make sure the top of the module says Option Explicit and that L is properly declared:
Dim L As Long
"L" being a meaningless identifier, you should consider naming it after what you're using it for:
Dim currentRow As Long
currentRow = 9
Do While Not IsEmpty(ActiveSheet.Cells(currentRow, "CT"))
That way your code becomes much easier to read, follow and understand.

Comparing cells using match in vba

I am trying to compare two columns of cells in vba using the match function. I am comparing the second column against values in the first and copying and pasting the values that aren't found to another column. I am doing the same with the second against the first as well. For some reason when I try to run this it says that it cannot get the match property of the worksheet function class and I am really confused as to why I am receiving this error. I have pasted the code below. Any help with this issue would be greatly appreciated.
Set PrevMonth = Sheet13.Range(Range("A2"), Range("A2").End(xlDown))
Set currMonth = Sheet13.Range(Range("B2"), Range("B2").End(xlDown))
Count = 2
For i = 2 To PrevMonth.Rows.Count
match = Application.WorksheetFunction.match(Cells(i, 1), currMonth, 0)
If WorksheetFunction.IsNA(match) = True Then
Sheet13.Cells(i, 1).Cut
Sheet13.Cells(Count, 3).Paste
Count = Count + 1
End If
Next i
For i = 2 To currMonth.Rows.Count
match = WorksheetFunction.match(Cells(i, 1), PrevMonth, 0)
If WorksheetFunction.IsNA(match) = True Then
Sheet13.Cells(i, 1).Cut
Sheet13.Cells(Count, 4).Paste
Count = Count + 1
End If
Next i
Can you try using
Application.Match(Cells(i, 1), currMonth, 0)
I know this should have been a comment...but I'm unable to comment as I'm below 50 Rep...
In my experience the "cannot get 'X' property of the worksheet function class" error is indicative that a poor argument has been passed to the worksheet function itself. In your case the arguments are: Cells(i, 1), currMonth. This likely means one of those ranges are inaccessible. If I had to guess, you want to be passing sheet13.cells(i,1). I'd recommend a 'with sheet13' statement for this whole segment of code. WorksheetFunction.Match in particular will throw that error if a match can't be found (VB doesn't work with the #N/A return value). Using a WorksheetFunction.CountIf > 0 can ensure there is a viable match within the range.
Also, Range("A2").End(xlDown) will result in the last cell of the column if there is no data after A2. This is generally unfavorable behavior.

How do I replace all error values in a column

I have a column which is populated using Index and Match functions and it results in a N/A value when the value is not found. I want to be able to replace all such error values from the column by a special value. I want to do this in VBA code. Any help?
I do not want to rewrite the function with an IF logic.
You really could do this without VBA, by the following:
IFERROR(myIndexMatchFormula,"special value")
If you really need a VBA solution, try something like the below. It will find all the error cells in your range and replace with something of your choice. No If statements, no loops!
Option Explicit
Sub replaceErrors()
Dim rng As Range
On Error Resume Next
Set rng = Range("A1:A10").SpecialCells(xlCellTypeFormulas, 16) ' -> replace with your specific range
rng.Value = "special values" '-> place what you want here
On Error GoTo 0
End Sub
Columns("E").SpecialCells(xlCellTypeFormulas, xlErrors).Value = ""
can replace all errors in column E, as an example.
However, unfortunately, specialcells always throws an error if it finds nothing, so you must catch this error via some on error ...
If r is the range which needs to be examined, you can always use the following to identify if the value in the cell is "N/A"
If r.Value = CVErr(xlErrNA) Then
... ' do something
Else
... ' do something else
Endif