Report Date as String won't convert to Long - excel

I've been banging my head on this issue! I have a variable called repDate which today is equal to "5/1/2020" as a string. I've tried this formula to convert it to a Long so I can compare it to a date in the file rDtLng = CLng(repDate). I'm getting error "Type Mismatch" which I am not sure why there would be one. This is where I am doing the comparing the rest works great, just the report date as long doesn't want to work.
'repDate equals "5/1/2020", currently
rDtLng = CLng(repDate)
.
.
.
'Delete charge offs
For w = rwCnt To 3 Step -1
Do While .Cells(w, napbRng.Column).Value2 <= 0 And .Cells(w, apbRng.Column).Value2 <= 0
If .Cells(w, matDtRng.Column).Value2 = "" Then Exit Do
If .Cells(w, matDtRng.Column).Value2 < rDtLng Then
.Rows(w).Delete shift:=xlShiftUp
Else: Exit Do
End If
Loop
Next w
Thanks in advance!

CLng expects a numeric input, which the text-that-looks-like-a-date "5/1/2020" is not.
You can convert that to an actual date using CDate and then perform mathematical operations on it, including the existing < comparison.
Though if I understand what your end goal is, you might consider Range.AutoFilter with a date filter, and then deleting visible rows, instead of your current Do loop approach.
Side note: you could CLng(CDate("5/1/2020")) and the result would be 43952, but that's an unnecessary step, as you can do math with dates directly.

Use DateValue() Function.
Sub test()
Dim myDate As Long
Dim str As String
str = "5/1/2020"
myDate = DateValue(str)
If myDate = DateSerial(2020, 5, 1) Then
MsgBox "OK"
End If
End Sub

Related

Excal VBA - Format("7A", "00") outputs "00" while Format("7B", "00") results to the desired output of "7A". Why are they different?

I am trying to list hexadecimal values from 7F down to 00 per Excel row. I achieved it by doing the following code:
Sub ListDownHex()
Dim StartValue, i As Integer
Dim nRow As Long
Dim sh As Worksheet
Set sh = ActiveSheet
StartValue = 127 'memory location of 8051 RAM
nRow = 4
For i = StartValue To 0 Step -1
sh.Range("A" & nRow) = Format(Right$("00" & Hex(i), 2), "00")
nRow = nRow + 1
Next i
End Sub
except hex values that have "A" like "7A", "6A", "5A", etc. result to "00".
Further check on Intermediate Window confirms Format() function does it.
? Format("7B","00") 'desired output
7B
? Format("7A","00") 'not expected output
00
Is this a bug or am I missing something? Why are they acting differently?
(Note: The focus of my question is on "strange" behavior of Format() not on my entire code.)
Format() is a complicated function that formats all sorts of things, dates and numbers included.
When you pass a string to it (which "7A" and "7B" are), it tries to see whether they can be converted to a number (IsNumeric() returns True) or a date (IsDate() returns True). If they can, it converts them, and only then applies formatting.
IsDate() returns True for "7A", which is because "7A" is valid textual representation of time value "7 in the morning" (7am).
That, in turn, is because the short version of the AM/PM formatting token, A/P, returns the "am/pm" designator as "a/p":
? Format$(#07:00:00#, "hA/P") ' => 7A
? Format$(#17:00:00#, "hA/P") ' => 5P
So the string "7A" is first converted to a Date value #12/30/1899 07:00:00# (zero date, 7 in the morning). The numeric representation of that value is 0.29166667, which, when formatted according to the "00" format, rounds to "00".
"7B", on the other hand, is not an IsDate(), so Format outputs it without changes like it does to strings that have no other meaning.
In reality though, you do not need the Format() function at all, all you need is
= Right$("00" & Hex$(i), 2)
Wow! so clear, and so complete. Thank you, #GSerg!
Allow me to refer to an error in exactly this regard made by Microsoft Support.
The following code was taken directly from Microsoft Support.
Function StrToHex (S As Variant) As Variant
'
' Converts a string to a series of hexadecimal digits.
' For example, StrToHex(Chr(9) & "A~") returns 09417E.
'
Dim Temp As String, I As Integer
If VarType(S) <> 8 Then
StrToHex = S
Else
Temp = ""
For I = 1 To Len(S)
Temp = Temp & Format(Hex(Asc(Mid(S, I, 1))), "00")
Next I
StrToHex = Temp
End If
End Function
The URL is
https://support.microsoft.com/en-us/office/sort-records-in-case-sensitive-order-8fea1de4-6189-40e7-9359-00cd7d7845c0

Extracting digits from strings in excel with condition

Say we have strings like this and want to output digits out from it. The digits is not always in the beginning so I think I need to define condition as well.
Tried this Excel: Extract Numbers from Date Strings
but not working
how can we extract the digits from this kind of string in excel?
Congrats, today is the day you are going to add some vba knowledge to your arsenal. This is how the result would look, if you add a vba formula to it:
In order to add the formula, press Alt+F11 and paste the following code either in Modul1 or in the Worksheet:
Public Function ExtractString(myRange As Range) As String
Dim i As Long
Dim result As String
Dim currentString As String
Dim okIndex As Long
okIndex = 1
result = ""
For i = 1 To Len(myRange.Text)
currentString = Mid(myRange.Text, i, 1)
If IsNumeric(currentString) And okIndex >= 1 Then
result = result & currentString
okIndex = okIndex + 1
Else
If okIndex > 1 Then okIndex = -1
End If
Next
ExtractString = result
End Function
If you prefer a formula solution, you can use:
=AGGREGATE(14,6,--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),ROW(INDEX($A:$A,1):INDEX($A:$A,LEN(A1)))),1)
If you have O365 with the most recent updates, you can use:
=AGGREGATE(14,6,--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),SEQUENCE(LEN(A1))),1)
If you need to check for no-digits in the string, you can wrap the formula in IFERROR. eg:
=IFERROR(AGGREGATE(14,6,--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),SEQUENCE(LEN(A1))),1),"")

Having issue with year() function

Im trying to create a module to pull data from a giant spreadsheet that I have on another sheet by year. Every part of the code works except for the part that matches the year to a user entered year.
Here's how I defined the user input and how I tried to write the if statement.
Dim y As variant
y = InputBox("Input year here")
If Year(RptSht.Cells(i, 2)) = y
At this point I get a type mismatch (I've tried setting y as an integer instead). Also just as a note I can use
Year(RptSht.Cells(i, 2))
to get a value, it just mismatches with y. Any help would be appreciated.
If Year(RptSht.Cells(i,2)) = y
That's doing too many things. Split it up.
First you want to get the cell at (i, 2):
Dim yearCellValue As Variant
yearCellValue = RptSht.Cells(i, 2)
Now, we can't just assume that yearCellValue is a valid date. We have to know it, otherwise if anything is wrong with the assumption, we'll likely run into a type mismatch error. Use the IsDate function to make sure you're looking at a Date value:
If IsDate(yearCellValue) Then
End If
Inside that conditional block, Year(yearCellValue) is safe. Outside of it, it isn't.
If IsDate(yearCellValue) Then
If Year(yearCellValue) = y Then
'...
End If
End If
Problem is, we don't know that y is a valid value either.
Dim y As variant
y = InputBox("Input year here")
If Not IsNumeric(y) Then Exit Sub 'bail out, we can't go any further.
Here is one way to handle the issue:
Sub gotimm()
Dim y As Long, RptSht As Worksheet, i As Long
y = Application.InputBox(Prompt:="Input year here", Type:=1)
Set RptSht = ActiveSheet
i = 1
With RptSht
If IsDate(.Cells(i, 2)) Then
If .Cells(i, 2) = y Then
MsgBox "match"
Else
MsgBox "nomatch"
End If
Else
MsgBox "no date in cell " & .Cells(i, 2).Address
End If
End With
End Sub
I guess the problem is that i is not assigned or (i,2) is not a date. Try this:
Sub TestMe()
Dim y As Variant
Dim i As Long
y = InputBox("Input year here")
i = 5
If IsDate(Worksheets(1).Cells(i, 2)) Then
If Year(Worksheets(1).Cells(i, 2)) = y Then
'Logic here
End If
End If
End Sub
Thus, the i is 5 and the reference cell is B5. The IsDate() checks whether the cell is a date.

How do I get VBA to recognize "001" for my loop?

I'm making a basic loop as follows:
Sub IntegerTestforSuffixFinder()
Dim i As Double
i = 1
MsgBox (i)
Do While i < 100
i = i + 1
If vbOK Then
MsgBox (i)
Else: End
End If
Loop
End Sub
This works just fine...but would I really need it to do for the actual problem I'm about to tackle is recognize i = 001. The zeroes are important place holders in this context, but it keeps correcting me to i = 1. Is there a way to stop this?
Much thanks!
You wouldn't. And you can't. But you can use the original Integer in your loop, and create a string that you can display. Try this and see if you can pull what you need from it:
Sub IntegerTestforSuffixFinder()
Dim i As Double
i = 1
MsgBox (i)
Do While i < 100
i = i + 1
If vbOK Then
'Original integer
MsgBox (i)
'3-character string created by using the Right() function
MsgBox Right("000" & i, 3)
Else: End
End If
Loop
End Sub
BTW, in your original example you realize you're starting your MsgBox at 2? You set i = 1, then you're adding 1 to it before displaying the first MsgBox. I'm thinking you probably want to move that i = i + 1 line to just before the Loop.
Try this:
Format cell - Custom. Look for Type with a "0". Type three "0" as below:
The value remains as integer.

Function to merge excel data referencing a count using VBA

I'm trying to write a function that merges multiple rows of text in a column into a single cell based on a pre determined count. My goal is to generate a flexible function to aid in compiling / interperting large quantaties of data. The code I've written returns #NAME? and I cant figure out where the error is. My code is as follows:
Function vmrg(countref As Integer, datref As Integer) As String
If IsEmpty(ActiveCell.Offset(0, -countref)) Then % check if cell containing count is blank
vertmerge = "N/A" % if blank, state N/A
Else
Dim datlst(0 To ActiveCell.Offset(0, -countref).Value - 1) As String
Dim i As Integer
For i = 0 To ActiveCell.Offset(0, -countref).Value - 1
datlst(i) = ActiveCell.Offset(i, -datref).Text %fill array with data
End
vertmerge = datlst(0)
For i = 1 To ActiveCell.Offset(0, -countref).Value - 1 % merge array to a single string
vertmerge = vertmerge & ", " & datlst(i)
End
End
End Function
I have matlab and some C++ experience but this is the first time I've used VBA so my syntax is probably odd in some areas and wrong in others. Ideally I would like to reference the cells where the data and count info are stored, but for now I'm hoping to correct my syntax and set a jumping off point for further development of this function. Any reccomendations are appreciated.
Code Rev_1: I still have an output of #NAME? but I think I've corrected(?) some of the issues
Function vertmerge(countref As Range, datref As Integer) As String
If IsEmpty(countref) = True Then
vertmerge = "NA"
Else
Dim datlst(0 To countref.Value - 1) As String
Dim i As Integer
For i = 0 To countref.Value - 1
datlst(i) = countref.Offset(i, datref).Text
Next i
vertmerge = datlst(0)
For i = 1 To countref.Value - 1
vertmerge = vertmerge & ", " & datlst(i)
Next i
End
End Function
You are doing some dangerous things here!
First - you are referencing "ActiveCell" from inside a function; but you have NO IDEA what cell will be active when the function runs! Instead, pass the target cell as a parameter:
=vmrg("B6", 5, 6)
and change your function prototype to
Function vmrg(r as Range, countref as Integer, datref as Integer)
Now you can reference things relative to r with
r.Offset(1,2)
etc.
Next - you are never assigning anything to vmrg. In VBA, the way a function returns a value is with (in this case)
vmrg = 23
You are assigning things to a variable called vertmerge - but that is not the name of your function. At least add
vmrg = vertmerge
Just before returning. That might do it. Without a full sample of your spreadsheet I can't help you more.

Resources