Getting Error of "Invalid procedure call or argument" at VBA - vba

I am new to vba and i have encountered into some problems.
I want to look up something from another worksheet and copy the match value to the other cell
VBA said it was the last code having problem.
Private Sub ReferenceOk_Click()
Dim nextRefRec As Integer
Dim i As Integer
Dim ListNo As Integer
ListNo = ListBoxBook.ListIndex
If ListNo < 0 Then
MsgBox "Please select any book"
Exit Sub
End If
Sheets("Rental History").Activate
nextRefRec = Cells(Rows.Count, 2).End(xlUp).Row + 1
For i = 0 To 1
Cells(nextRefRec, i + 3).Value = ListBoxBook.List(ListNo, i)
Next i
Cells(nextRefRec, 3).NumberFormat = "0000"
Cells(nextRefRec, 2).NumberFormat = "00000"
Cells(nextRefRec, 2).Value = TxtMemberNo.Value
Cells(nextRefRec, 5).Value = Date
Cells(nextRefRec, 6).Value = Date + TxtRentalDays.Value
Cells(nextRefRec, 7).Value = Application.WorksheetFunction.VLookup(Worksheets("Rental History").Cells(nextRefRec, 4), Worksheets("Book List").Cells("B4:C24"), 6, False)
End Sub

Your VLOOKUP formula:
VLookup(Worksheets("Rental History").Cells(nextRefRec, 4), Worksheets("Book List").Cells("B4:C24"), 6, False)
seems invalid.
The range Worksheets("Book List").Cells("B4:C24") contains 2 columns, but your third argument is 6. In other words, you are attempting to get the 6th column of a 2-column range (which obviously doesn't exist). So at the moment it's probably returning a #REF error.
Further info on VLOOKUP if needed: https://support.office.com/en-us/article/vlookup-function-0bbc8083-26fe-4963-8ab8-93a18ad188a1
Fix your VLOOKUP formula so that you're passing a column that at least exists within the range you pass as the second argument.
Also, I recommend declaring these variables as type Long (to prevent type overflow errors):
Dim nextRefRec As Integer
Dim i As Integer
Dim ListNo As Integer
and changing this line:
Cells(nextRefRec, 7).Value = Application.WorksheetFunction.VLookup(Worksheets("Rental History").Cells(nextRefRec, 4), Worksheets("Book List").Cells("B4:C24"), 6, False)
to this (except also fix your VLOOKUP arguments as mentioned above):
Cells(nextRefRec, 7).Value = Application.VLookup(Worksheets("Rental History").Cells(nextRefRec, 4), Worksheets("Book List").Cells("B4:C24"), 6, False)
so that if VLOOKUP returns #N/A or some other error, the error value can be written to the cell instead of interrupting your macro.
Your code implicitly refers to whatever sheet happens to be active whilst the code is running. Try to refer to the parent workbook and worksheet (in case the sheet that's active isn't the one that you think it is).

Related

VBA error "Unable to get the Hex2Dec property of the WorksheetFunction class

I am working on a code that copies certain cell values from a workbook to another workbook. The twist is that the information is in hexadecimal in one workbook and I need to convert the value in decimal when I copy it to the other workbook.
What is weird is that everything works perfectly and the code copies and then adds the value, converted in the workbook needed; all until it reaches the last row and that's where I get the error. (the error shows up at the line that has a comment added)
Debug.Print Now
varSheetA = varSheetA.Range(RangeA)
Debug.Print Now
i = 1
For rowN = LBound(varSheetA, 1) To UBound(varSheetA, 1)
Tst = Mid(wbkB.Worksheets("CopyFromHere").Cells(rowN + 1, 2).Value, 3, 6)
Set Rng = wbkA.Worksheets("Sheet1").Range(RangeA).Find(Tst)
If Rng Is Nothing Then
i = i + 1
wbkA.Worksheets("Sheet2").Cells(i, 5).Value = WorksheetFunction.Hex2Dec(wbkB.Worksheets("CopyFromHere").Cells(rowN + 1, 5).Value) 'error is here
End If
Next
I need to mention that some of the values that are in hexadecimal are these (just to have an idea): 239, 7E101, 7FA3A, B38
And the value that currently the program gives error is B38
I don't understand why this happens, as the code runs perfectly well until that value/last row. I don't know which one is the problem.
Clean the "cell" before like that
wbkA.Worksheets("Sheet2").Cells(i, 5).Value = _
WorksheetFunction.Hex2Dec(Trim(wbkB.Worksheets("CopyFromHere").Cells(rowN + 1, 5).Value))

Excel VBA: Run Time Error '13' Type mismatch when trying to loop through column

Good morning all,
I am stumped on why I am getting a type mismatch when trying to loop through column A with a For each loop.
Sub timeStart()
Dim s As Worksheet
Dim anchor As Range
Dim i As Variant
i = 2
Set s = Workbooks("ER911 CALLBACKS SHEET").Sheets("Time Log")
For Each i In s.Range("A:A")
If s.Cells(i, 1).Value = "" Then 'ERROR OCCURS HERE
s.Cells(i, 1) = Date
s.Cells(i, 1).Offset(0, 1) = InputBox("What is your name?")
s.Cells(i, 1).Offset(0, 2) = InputBox("What program are you calling on?")
s.Cells(i, 1).Offset(0, 3) = Time()
Exit For
End If
Next i
End Sub
Your problem is here:
For Each i In s.Range("A:A")
In this case each i is a Range object the represents the next cell in the sequence.
But then you are trying to use the range object as a row # in s.Cells(i, 1). So instead you should just use the range object you created:
For Each i In s.Range("A:A")
If i.Value = "" Then 'ERROR OCCURS HERE
i = Date
i.Offset(0, 1) = InputBox("What is your name?")
i.Offset(0, 2) = InputBox("What program are you calling on?")
i.Offset(0, 3) = Time()
Exit For
End If
Next i
As Alex K points out, you would be much safer to define your i as a Range initially Dim i as Range and then you would be sure to always use i correctly. You would then need to remove your i = 2 line as it not needed and would actually cause a different Type Mismatch error
Another suggestion would be to rename i to something more understandable so when reading this code 6 months from now, it is immediately clear what i represents.
Just simply:
For i = 1 to N ' N = whatever the last row you wish to be
If s.Cells(i, 1) = "" Then
... and so on
or
Dim rX as range
For Each rX in s.Range("A:A") ' WARNING! there are too many cells here in the column, BTW
If rX = "" Then
... and so on

Use match formula in vba to return a row number

I have been trying this for quite sometime and although I get the correct answer but I get an Application-defined or Object defined error.
I have two sheets: Sheet2 and Sheet3. Both the sheets have a column "url". What I want is to get the row number of the url in Sheet2 and get the urls row position printed in
Column C ("Match Row") of Sheet3.
This is the example of the data I am working on.
I get the error in this line
Matchvalue.Formula = "=Match(Worksheets("Sheet3").Cells(i, 2), Worksheets("Sheet2").Range("B:B"), 0)
This is what I've tried:
Dim i As Integer
i = 2
Do While Worksheets("Sheet3").Cells(i, 2) <> ""
Worksheets("Sheet3").Cells(i, 14) =
WorksheetFunction.Match(Worksheets("Sheet3").Cells(i, 2),
Worksheets("Sheet2").Range("B:B"), 0)
i = i + 1
Loop
Try the code below, explanations inside the code's comments:
Option Explicit
Sub MatchUrl()
Dim i As Long
Dim MatchRng As Range
With Worksheets("Sheet2")
' set the match range is "Sheet2"
Set MatchRng = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row)
End With
With Worksheets("Sheet3")
For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
' check if successful match
If Not IsError(Application.Match(.Cells(i, 2), MatchRng, 0)) Then
.Cells(i, 2) = Application.Match(.Cells(i, 2), MatchRng, 0)
Else ' Match failed, raise some kind of error
.Cells(i, 2) = "Url not found in Sheet2!"
End If
Next i
End With
End Sub
i don't use Match so I don't know the Signature of it but :
By escaping Quotes perhaps ... like
Matchvalue.Formula = "=Match(" & Worksheets("Sheet3").Cells(i, 2) & ";B:B;0)"
To escape quotes just double them.
for example Debug.print "Hey ""You"" how are you ?"

"Sub or Function not defined" vba

VBA novice here
When I run my code I receive the error "Sub or Function not defined". This occurs in one of my subroutines. The first line is highlighted in yellow by the debugger.
Sub Description(Row As Integer, SheetName As String)
With Worksheet(SheetName)
.Cells(Row, 1) = ActiveCell.Offset(0, -3)
.Cells(Row, 2) = ActiveCell.Offset(0, -2)
.Cells(Row, 3) = ActiveCell.Offset(0, -1)
End With
End Sub
This subroutine takes in a number and a string. I want to copy specific descriptions into into another worksheet "SheetName". Here is a piece of the code prior to the subroutine call. The value of "x" is declared outside the loops scope.
string_temp = "Sheet2"
ActiveSheet.Cells(i, 5).Select
Call Description(x, string_temp)
x= x + 1
Appreciate the help!
With Worksheet(SheetName) should be With Worksheets(SheetName)
Also change Row As Integer to Row as Long, Integer is actually marginally slower in VBA as the compiler converts it to a Long for processing.

For loop terminates after the first iteration -Excel VBA

I am trying to do a simple loop, where I have declared some variables as array entries. I originally used them as variables to be overwritten, but changed it when I read that these variables will not automatically overwrite each time through the loop.
My problem is that this loop terminates after the first iteration (with no error). I can't seem to figure out why...
The code is essentially to find cons_sum(i,2) for each i, or row in the Pre-Summary sheet and sum some data in another sheet BOPE, then insert that sum into Pre-Summary.
This is my first post and I am teaching myself vba so please excuse any code fails.
This is my code:
Option Explicit
Sub Create_GAR080()
Consmonth = Sheets("GAR080").Range("B2").Value
Sheets("Pre-Summary").Select
LastRow_summary = Cells(Rows.Count, "A").End(xlUp).Row
LastRow = 156
LastCol = 16
Dim cons_sum() As Variant
ReDim cons_sum(LastRow_summary, 4)
For i = 1 To LastRow_summary Step 1
cons_sum(i, 1) = Cells(i, 2).Value & "" 'pulls participant
cons_sum(i, 2) = cons_sum(i, 1) & Cells(i, 1) ' participant and gas gate concatenated
If cons_sum(i, 1) = "BOPE" Then
Sheets(cons_sum(i, 1)).Select
cons_sum(i, 3) = WorksheetFunction.Match(cons_sum(i, 2), Sheets(cons_sum(i, 1)).Range("A:A")) ' find participant gas gate combo
cons_sum(i, 4) = Application.Sum(Sheets(cons_sum(i, 1)).Range(Cells(cons_sum(i, 3), 5), Cells(cons_sum(i, 3), 16)))
If cons_sum(i, 4) > 0 Then
Sheets("Pre-Summary").Cells(i, 4).Value = cons_sum(i, 4)
End If
End If
Next i
On Error Resume Next
End Sub
As Siddharth points out, your changing of sheets will result in cons_sum(i, 1) = "BOPE"to always be negative. Therefore, while the loop will run 1,848 times, it will not change anything.
In addition, a few more remarks:
You are using a 1848x4 array to do multiple operations in each line - but only stored the value of each operation and not use the array afterwards. Thus, you do not need 1848x4, but only 1x4, as you can reuse the variables
Instead of using an array, it is much better to use speaking variables. This will make your code much easier to understand
You have a lot of assumptions about the workbook structure hidden in the VBA formulas/statements, e.g. the number of rows, the name "BOPE", etc.. It is better to store them in constants in the beginning of the macro - or even better to store them somewhere on a settings sheets and refer to them with named ranges
You most likely forgot FALSE (or 0) as the third parameter for your match function. Therefore the function might return the wrong values if the column is not sorted
Instead of Range(Cells(x1,y1),Cells(x2,y2)) you can use Range.Resize and Range.Offset (and combinations thereof). This makes the code much easier to read!
do not use On Error Resume Next unless you know exactly what error you are happy to neglect! Even if you use it, use another On Error statement right after the operation that is allowed to produce an error.
Taking this into account, I reworked your code to the following:
Sub Create_GAR080_reworked()
Const cStrTerm As String = "BOPE"
Dim wsData As Worksheet
Dim lngRowCount As Long, i As Long
Dim strParticipantGasID As String
Dim lngParticipantGasCombo As Long
Dim dblSum As Double
Set wsData = Sheets(cStrTerm)
With Sheets("Pre-Summary")
lngRowCount = .Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lngRowCount
If .Cells(i, 2) = cStrTerm Then
strParticipantGasID = cStrTerm & .Cells(i, 1) ' participant and gas gate concatenated
lngParticipantGasCombo = WorksheetFunction.Match( _
strParticipantGasID, wsData.Range("A:A"), 0) ' find participant gas gate combo
dblSum = Application.Sum( _
wsData.Range("E1:P1").Offset(lngParticipantGasCombo - 1))
If dblSum > 0 Then
.Cells(i, 4).Value = dblSum
End If
End If
Next i
End With
End Sub
As I do not have your worksheet, I couldn't debug it. Also, not sure if I hit the right names as I have no idea what each variable is really refer to. But it should give you a start.
If the first itiration the code Sheets(cons_sum(i, 1)).Select is hit, you'll never get back to the Pre-Summary sheet.
Try:
Option Explicit
Sub Create_GAR080()
Consmonth = Sheets("GAR080").Range("B2").Value
Sheets("Pre-Summary").Select
LastRow_summary = Cells(Rows.Count, "A").End(xlUp).Row
LastRow = 156
LastCol = 16
Dim cons_sum() As Variant
ReDim cons_sum(LastRow_summary, 4)
For i = 1 To LastRow_summary Step 1
Sheets("Pre-Summary").Select
cons_sum(i, 1) = Cells(i, 2).Value & "" 'pulls participant
cons_sum(i, 2) = cons_sum(i, 1) & Cells(i, 1) ' participant and gas gate concatenated
If cons_sum(i, 1) = "BOPE" Then
Sheets(cons_sum(i, 1)).Select
cons_sum(i, 3) = WorksheetFunction.Match(cons_sum(i, 2), Sheets(cons_sum(i, 1)).Range("A:A")) ' find participant gas gate combo
cons_sum(i, 4) = Application.Sum(Sheets(cons_sum(i, 1)).Range(Cells(cons_sum(i, 3), 5), Cells(cons_sum(i, 3), 16)))
If cons_sum(i, 4) > 0 Then
Sheets("Pre-Summary").Cells(i, 4).Value = cons_sum(i, 4)
End If
End If
Next i
On Error Resume Next
End Sub