Excel VBA: Type Mismatch explanation - vba

I'm a newcomer to VBA so was hoping someone with more experience could please explain why I receive a
Type Mismatch error
against the following:
Private Sub cbbWeek_Change()
txtWeekEnding = Application.VLookup(cbbWeek.Value, Worksheets("Formulas").Range("Q1:R53"), 2, False)
End Sub
I'm not sure if it's relevant but;
Column Q contains numbers from 1 (in cell Q1) to 52 (in cell Q52)
Column R contains dates formatted to dd/mm/yyyy

To see whether VLookup returns an error or not - assign the returned value to a variable. Check if the variable is an error, and if it is not an error - assign it to txtWeekending:
Private Sub TestMe()
Dim checker As Variant
Dim txtWeekending As Variant
checker = Application.VLookup("vityata", Range("A1:C53"), 2, False)
If Not IsError(checker) Then
Debug.Print checker
txtWeekending = checker
Else
Debug.Print checker
End If
End Sub
This is an article from CPearson, concerning the same problem.

Related

VLookUp not working - Property could not be assigned

My problem is, that when using the VlookUp I do get the Error:
The VLookup-Property of the WorksheetFunction-Object could not be assigned
' LookUp missing Data
Dim lookupRange As Range
Set lookupRange = Sheets("Kundenlisten HLK 2018").Range("A1:Y10354")
' Fill in Companyname
Dim tmp As String
tmp = Values(0)
tmp = TrueTrim(tmp)
testing.Cells(8, counter) = Application.WorksheetFunction.VLookup(tmp, lookupWS.Range("A2:Y10354"), 2, False)
Values = None
counter = counter + 1
lookupWS is the Name of the Worksheet
As you can see the table I am trying to lookup is filled with values from A to Y. The first column is the key I am trying to look up, but then the error from above occurs. The tmp variable is a String with a unique ID to look up the missing values, while the "2" is supposed to be the company name in the second column of the Range.
I looked up on the docs, but the types and everything are fine, I even checked while debugging.
testing.Cells(8, counter) can't be the source of the problem aswell, since I am using it before like this
testing.Cells(28, counter) = Left(mail.ReceivedTime, 10)
and it works
It's difficult to know what the problem is without any data, but here's something to help you in the right direction.
It's better to use Find and Offset than
WorksheetFunction.Vlookup in VBA
Something like this gives you exactly the same result, but you have much more control:
Sub Test()
Dim valueFound As Range
Set valueFound = lookupWS.Range("A2:A10354").Find(What:="Something", lookat:=xlWhole) 'xlWhole is equivalent to FALSE in VLOOKUP
If valueFound Is Nothing Then
MsgBox "Nothing found"
Else
MsgBox valueFound.Offset(0, 1) 'offsetting by 1 is equivalent to using 2 in a VLOOKUP
End If
End Sub

Error 2042 When Using Vlookup To Find Date in VBA

I am trying to write code that looks up a batch ID based on the date entered in the "TSDate" field.
I keep getting error 2042 when trying to use the Application.VLookup Function in VBA:
'Timesheet Date
Private Sub TSdate_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal shift As Integer)
Dim TimesheetDate As Date
Dim batch As Variant
Dim DRange As Range
Set DRange = Range("Table_PayPeriods")
If KeyCode = 13 Or KeyCode = 9 Then
TSDate.Value = Format(TSDate.Value, "dd-mmm-yy")
TimesheetDate = TSDate.Value
batch = Application.VLookup(TSDate.Value, DRange, 2, 0)
MsgBox (DRange(2, 2))
BatchID.Text = batch
End If
End Sub
The messagebox proves that the data being looked up is being pulled properly, the problem is I am getting the error in the "batch" variable.
Any help would be appreciated. Thanks!
Application.VLookup will return Error 2042 when the lookup value is not found.
You need to test for error, and handle appropriately:
If KeyCode = 13 Or KeyCode = 9 Then
TSDate.Value = Format(TSDate.Value, "dd-mmm-yy")
TimesheetDate = TSDate.Value
batch = Application.VLookup(TSDate.Value, DRange, 2, 0)
If IsError(batch) Then
'Do something
Else
MsgBox (DRange(2, 2))
BatchID.Text = batch
End If
End If
As for why the value is not found, it's not possible to answer without more detail from you regarding the input data and respective formats -- perhaps the value really doesn't exist, or perhaps it appears to exist but really does not: (generally I would expect a string will not match a date type and vice-versa).
If the cells contain Date type values (even if they are formatted to look like strings, an Error is expected. In this case, convert the string input (TSDate.Value) to a Date type, and convert that to a Long type and do the Vlookup with its long numeric equivalent:
batch = Application.VLookup(CLng(CDate(TSDate.Value)), DRange, 2, 0)
You'll still need Error handling in the event that the date value literally doesn't exist in the table.

Why is assigning the Value property of cell causing code to end aburptly?

Private Sub FillRow(programCell As Range, storedProgramCell As Range)
Dim counter As Integer
For counter = 3 To 9
Dim cellOffset As Integer
cellOffset = counter - 3
Dim currentStoredCell As Range
Set currentStoredCell = storedProgramCell.Offset(0, cellOffset)
Dim value As String
value = currentStoredCell.value
Dim currentTargetCell As Range
Set currentTargetCell = programCell.Offset(0, cellOffset)
MsgBox currentStoredCell.value 'Works correctly, prints correct value
currentTargetCell.value = value
Next counter
End Sub
The line:
currentTargetCell.value = value
causes the code to stop executing, with no error.
I added the expression to my watch list, then stepped through the routine. The expression was seen as a Boolean:
This makes me think the expression is being viewed as a comparison, and the program abruptly ends since the returned Boolean is not being stored or used anywhere. I wouldn't doubt if I were wrong though.
I'm new to VBA, struggling to debug my program, so please forgive me if this is a petty mistake. I couldn't find any sources online that explains this problem.
Replace your subroutine with following code:
Private Sub FillRow(Dst As Range, Src As Range)
Dim x As Integer
Dim v As Variant
Dim Srcx As Range
Dim Dstx As Range
Debug.Print "FillRow"
Debug.Print Src.Address
Debug.Print Dst.Address
Debug.Print "Loop"
For x = 0 To 6
Debug.Print x
Set Srcx = Src.Offset(0, x)
Debug.Print Srcx.Address
v = Srcx.Value
Debug.Print TypeName(v)
Set Dstx = Dst.Offset(0, x)
Debug.Print Dstx.Address
Dstx.Value = v
Next
Debug.Print "Completed"
End Sub
Run and post in your question Immediate window output.
Value is a reserved word, even if vba does not raise an error on this name, you should not use it. Name it something else. Also, try setting it as a variant.

Simple single cell populate with Vlookup value

I am fairly new to VBA, I couldn't really find answer specific to my simple request (most answers were a lot more complicated....). I would like Cell E2 to populate with the result of the vlookup. Is there a simple way to do this?
Thanks and sorry if I failed to find a suitable answer..
Sub vlookup_customerror()
Worksheets("customerror").Activate
On Error GoTo Errormsg
Hobbyquery = Application.WorksheetFunction.VLookup(Range("E1"),
ActiveSheet.Range("A2:B5"), 2, 0)
Cells("E2").Value = Hobbyquery
GoTo ending
Errormsg: GoTo ending
ending: End Sub
Please try This: You can add error handler code also
Sub custom_error()
Dim result As Integer
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("customerror")
Name = sheet.Range("E1").Value
result = Application.VLookup(Name, sheet.Range("A2:B5"), 2, False)
sheet.Range("E2").Value = result
Debug.Print result
End Sub
If you have string data in Column B then change Dim result As String
EDIT : To cover the situation , if the lookup value is on other sheet as per
apprehension expressed by #MacroMarc. In that case please try This:
Sub custom_error_v2()
Dim result As Variant
On Error Resume Next
result = Application.WorksheetFunction.VLookup(Range("E1"), _
Worksheets("Sheet1").Range("A:C"), 2, False)
On Error GoTo 0
If IsEmpty(result) Then
MsgBox "Value not found!"
End If
Range("E2") = result
End Sub
Images of sample data are appended below.
Please make changes to sheet names as per your requirement.

VBA Excel string datatype variable assignment

I am trying to set a value for CurrentClient Variable i have defined below and then using it to count how many times it Occurs in a range. I am not sure what am i doing wrong here . It is giving me error: "runtime error 9 subscript out of range" on step where it is assigning the value from Sheet 2 cell A2 to Currentclient.
Please help.
Sub GetValue()
Dim ClientCnt As Integer
Dim CurrentClient As String
CurrentClient = Sheets("Sheet 2").Range("A2").Text
ClientCnt = Application.WorksheetFunction.CountIf(Range("A:A"), CurrentClient)
End Sub
Use Sheet2
rather than
Sheet 2