VBA Excel string datatype variable assignment - vba

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

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

Excel VBA: Type Mismatch explanation

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.

lookup a number and increment value in another cell within same row

I would like to create a macro in excel that lets me increment the counts of a part whenever I press a command button.
Currently, my concept is to use vlookup to get the existing counts for that part using the following. However, it does not increment the actual counts value in the cell, which is what I want. I suspect it's cos vlookup is only used to return a value within the cell, but the cell is not activated in the process for actual increment. Can someone please advise how I can correct it? I'm still new to vba. Thanks!!! :)
E.g. Vlookup finds C1value in Cell A5 of Sheets("Location"). It will automatically increment the value in Cell C5 by 1.
Sub FindAddTools()
Dim C1Qnty As Double
C1value = Sheets("Issue").Range("D11")
Sheets("Location").Activate
C1Qnty = WorksheetFunction.VLookup(C1value, Range("A:D"), 3, False)
C1Qnty = C1Qnty + 1
End Sub
ADD ON: an add-on to my original question. I was wondering if it is possible to do the same for an entire range?
E.g. C1value is now a range of Sheets("Issue").Range("D11:D20"). I want to find all values within this range in Sheets("Location") and increment their corresponding counts in Column C.
Is there a way to do this without repeating the same procedure for all cells of the range?
Thanks! :)
Here's my shot at it. If the value isn't matched nothing happens:
Sub FindAddTools()
Dim RangeToMatch As Excel.Range
Dim cell As Excel.Range
Dim C1Value As Variant
Dim C1Row As Variant
Set RangeToMatch = Sheets("Issue").Range("D2:D11")
For Each cell In RangeToMatch
C1Value = cell.Value
With Sheets("Location")
C1Row = Application.Match(C1Value, .Range("A:A"), 0)
If Not IsError(C1Row) Then
.Range("C" & C1Row).Value = .Range("C" & C1Row).Value + 1
End If
End With
Next cell
End Sub
I edited it so that it cycles through a range of cells to match. That range is set to D2:D11 above.
Based on your comments, I think this should do it.
NB: you don't have to Activate worksheets to perform the functions referencing their cells/ranges.
Sub FindAddTools()
Dim shIssue as WOrksheet: Set shIssue = Sheets("Issue")
Dim shLoc as Worksheet: Set shLoc = Sheets("Location")
Dim allC1Values as Range
Dim C1Value as Variant
Dim C1Qnty As Double
Dim foundRow as Long
Set allC1Values = shIssue.Range("D11:D100") '## Modify as needed.
For each C1Value in allC1Values.Cells
C1Qnty = WorksheetFunction.VLookup(C1value, shLoc.Range("A:D"), 3, False)
C1Qnty = C1Qnty + 1
foundRow = WorksheetFunction.Match(c1Value,shLoc.Range("A:A"),False)
shLoc.Range("C" & foundRow).Value = CqQnty
Next
End Sub
Be careful with this. You're immediately writing to the same cell you just "found" with the VLOOKUP function, so, obviously if you run this macro again, you're going to increment it again. But, this may be the desired functionality, if so, no problem.
NOTE: There is no error trapping for if C1Value is not found in the VLOOKUP or MATCH functions.

Why is VLookup in VBA failing with runtime error 1004?

Spreadsheet "Sheet3" looks like this:
S&P 500 DJIA
1/1/1991 795.4476 2973.09
1/2/1991 786.3856 2947.1
1/3/1991 775.4636 2905.19
1/4/1991 773.5364 2896.8
1/7/1991 760.2996 2847.9
1/8/1991 759.0029 2832.81
1/9/1991 750.8416 2788.67
1/10/1991 758.1719 2820.8
Also Cell "F2" is literally a copy and paste of 1/7/1991 cell.
VBA Code looks like this:
Sub badlook3()
Dim BenchSI As Variant
Dim BRange As Range
Dim SIDate As Date
Set BRange = Worksheets("Sheet3").Range("A2:C9")
MsgBox BRange.Address
SIDate = Worksheets("Sheet3").Range("F2").Value
BenchSI = Application.WorksheetFunction.VLookup(SIDate, BRange, 2, True)
End Sub
I am getting the "Unable to get the VLOOKUP property of the WorkSheet Function class" error.
What am I missing here? Column A is in the right order. They are dates. What does Excel want from me?
The problem is with using SIDate as Date(Visual Basic date type)
My guess would be that visual basic date type and excel date type do not match, that's why you're getting an error
Instead declare SIDate as a Range, and it will work
Here's the code:
Sub badlook3()
Dim BenchSI As Variant
Dim BRange As Range
Dim SIDate As Range
Set BRange = Worksheets("Sheet3").Range("A2:C9")
MsgBox BRange.Address
Set SIDate = Worksheets("Sheet3").Range("F2")
BenchSI = Application.WorksheetFunction.VLookup(SIDate, BRange, 2, True)
End Sub
You are asking vLookup to return on a 2 column range, against a 1 column range. Change BRange = "A2:B9" to make your vLookup pick up the S&P Value.
Alternatively, you can change the range to A2:C9 and change the 2 to a 3 in your vLookup and get the DJ average.
In short, vLookup can only return a column reference to the greatest amount of columns in a range. It can return the 1st, 2nd, 0r 3rd column reference in a 3 column range, but not the 4th, because there is no 4th column.

Excel VBA, over flow error

I am using VBA in my excel sheet and it gives me an overlfow error. When I checked I found out that it was related to data error which shows unilmited "#" character in one cell.
All values in each cell is assigned to a string variable and when this cell comes in generates an overflow error. I tried to validate this using an if condition, but whenever we check cell.value this generates an overflow error. Is there any way to fix this?
You will not get a runtime error if you just read the cell text:
s = Range("C2").Text
Debug.Print s
' returns: "###########"
If you really want to read the cell value, and not the cell text (why you would need this, I have no idea, since you're stuffing it in a String anyway) then this is a workaround, assuming the #### are caused by dates Jan 1, 10,000 AD or later.
Const MaxDateSerial As Double = 2958466
Dim s As String
Dim dbl As Double
Dim nf As Variant
' Save original number format
nf = Range("C2").NumberFormat
' Use read-safe number format to read cell content
Range("C2").NumberFormat = "General"
dbl = Range("C2").Value
' Restore original number format
Range("C2").NumberFormat = nf
If dbl < MaxDateSerial Then
s = Range("C2").Value
Else
s = "Date overflow!"
End If
If you are doing something like
Dim s as string
Dim cl as Range
...
s = cl
' or
s = cl.value
s will be set to the value as diplayed on the sheet, which includes an error
(in the form "Error <Error Code>" if that's what the sheet displays
If the underlying cell value is valid, you should be able to access if using cl.value2
If you are doing somthing like
Dim v as Variant
Dim s as string
Dim r as Range
...
Set r = <SomeRange>
v = r
...
And one or more cells in range r are an error, then Runtime Error 6 Overflow will occur
To advise further, please post details of the code, where the error occurs, cell value and cell formatting
The ############### display for dates occurs if the date serial is before 1/1/1900 (negative) or after 1/1/9999 (> 2958101) EDIT actually 31/12/9999 = 2958465
Try using the "ISERROR()" function to filter out the invalid values.
IF(ISERROR(A1),0,A1)