Inserting date as integer (Excel) - vba

I have a vba code to concatenate a values from different columns. One of the columns; column M - is date, in format dd/mm/yyyy. I would like to concatenate the integer value of date of this with other values in cells.
I am trying to use Int(CDbl("date")) to convert the date value to int, then use that to concatenate with other cells.
My current vba code is:
Dim datevar As Integer
For i = 1 to LastRow
datevar = Int(CDbl(Sheets("Project_Name").Cells(i, 13).value))
target.location.formula = "=Project_Name!B" & i & "&UPPER(Project_Name!D" & i & ")&Project_Name!E" & i & "&Project_Name!F" & i & "&Project_Name!G" & i & "&Project_Name!H" & i & "&Project_Name!I" & i & datevar & ""
Next i
When I run this, I get a "Type Mismatch" error on the datevar = Int(CDb1(...)) line:
Can someone please advise why I am getting an error, and if there is a more efficient way of working?
EDIT
OKay - I get the error as CDbl cannot convert String to Double... However, the value in that cell is definitely a date and not string. What is the best way to counter this issue?

Working with dates, you better store their value to Double and not Integer.
Just use:
datevar = Sheets("Project_Name").Cells(i, 13).Value
You can add the following line to protect against none-integer values:
If IsNumeric(Sheets("Project_Name").Cells(i, 13).Value) And Sheets("Project_Name").Cells(i, 13).Value > 0 Then
Note: you can use Double or Long to store date values.
Integer is limited to values up to 32,767, read HERE.
If we look at today's date, Aug-17-2018 value is 43,329, which is over the Integer upper limit, that's why you are getting your error.

To follow up on our conversation in the comments, heres a quick little example of that idea:
Sub test()
Dim cellValue As String
Dim spaceSpot As Integer
cellValue = CStr(ThisWorkbook.Worksheets(1).Range("A1").Value) ' which is 12/22/2018
spaceSpot = InStr(cellValue, " ")
' Checking if date is in format 12/22/2018 00:00:00
If spaceSpot > 0 Then
cellValue = Left(cellValue, spaceSpot - 1)
End If
cellValue = Replace(cellValue, "/", "")
MsgBox cellValue ' shows 1222018
End Sub

Related

VBA - Date Reference

I am new to VBA and have a pretty simple question. I built a macro that updates a data set periodically and one of the functions of the macro is that it checks to make sure that if there is data for a previous date that it replaces it.
It uses a cell reference to cross check the data set, however I found that if the date is nor formatted the same then it will not replace it. Ex. if 03/07/18 then it will not replace 03/07/2018.
Any ideas on what I could possibly do to circumvent this issue? Thank you in advance!
Here is the code I have for this part of the macro
Dim i As Integer, ValueToFind As Integer, LRow As Integer
intValueToFind = Sheet8.Range("L6")
Sheet3.Activate
LRow = Range("J" & Rows.Count).End(xlUp).Row
For i = 1 To LRow
If Cells(i, 10).Value = intValueToFind Then
MsgBox ("Found value on row " & i)
I might do something like this:
Dim i As Long, dateToFind As Date, LRow As Long, checkValue As Variant
dateToFind = CDate(Sheet8.Range("L6").Value)
Sheet3.Activate
LRow = Range("J" & Rows.Count).End(xlUp).Row
For i = 1 To LRow
checkValue = Cells(i, 10).Value
If IsDate(checkValue) Then
If dateToFind = CDate(checkValue) Then
MsgBox ("Found value on row " & i)
End If
End If
Next
It seems like you were declaring everything to be an integer, when it's not really. Also, I use Long data types out of habit, which is why I changed your two Integers (that ARE integers) to Longs.
VBA has a built in "Date" data type, which you can read more about here. Basically, we're assigning the date to dateToFind (a Date data type), and we're using the function CDate to force the value of cell L6 to be a Date data type.
Then, we're looping through your cells, and assigning the value to a variant. We're then checking that value to see if it's "like" a date, as determined by VBA's IsDate function. If it is, we'll force it into a Date data type with CDate, and check it against dateToFind.
Note, we had to check if the value was a date with IsDate before using CDate because if the cell value is NOT in a date format, forcing it to be a Date type will throw an error. We didn't check the first time because we can be reasonably confident that the specific date cell you're using (L6) is, in fact, a Date.
Hopefully that works for you.
Did you try to clear and reapply date format ?
Something like this :
Dim i As Integer, ValueToFind As Integer, LRow As Integer
'Clear and apply a date format
Sheet8.Range("L6").ClearFormats
Sheet8.Range("L6").NumberFormat = "yyyy/mm/dd"
Columns(10).Select
Columns(10).ClearFormats
Columns(10).NumberFormat = "yyyy/mm/dd"
intValueToFind = Sheet8.Range("L6")
Sheet3.Activate
LRow = Range("J" & Rows.Count).End(xlUp).Row
For i = 1 To LRow
If Cells(i, 10).Value = intValueToFind Then
MsgBox ("Found value on row " & i)

Excel VBA : How to Compare specific String

I had came up with some problem that i not sure on how to compare string.
Example
Dim DateStart as String
Dim CompareDate as String
DateStart = "01-05-15"
In CompareDate i type in a value 02-05-15, how can i compare the 01-05 with 02-05?
I do not want to use Dim DateStart as Date.
And also how can i compare Column instead of Row?
The current code i using for comparing row is :
iRow = ws.Cells.Find(what:="*", After:=ws.Range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
how can i compare the 01-05 with 02-05
Since you are doing a String match, try this
Sub Sample()
Dim DateStart As String
Dim CompareDate As String
CompareDate = "02-05-15"
DateStart = "01-05-15"
If Left(DateStart, (InStrRev(DateStart, "-", -1, vbTextCompare) - 1)) = _
Left(CompareDate, (InStrRev(CompareDate, "-", -1, vbTextCompare) - 1)) Then
MsgBox "Matches"
Else
MsgBox "Doesn't Match"
End If
End Sub
The InStrRev function returns the position of the first occurrence of a string (- in your case) in another string, starting from the end of the string.
Or you could you this simple code
If Left(DateStart, 5) = Left(CompareDate, 5) Then
MsgBox "Matches"
Else
MsgBox "Doesn't Match"
End If
Regarding your second question, I am sorry, I didn't understand what are you trying to achieve. Perhaps if you rephrase it?
Edit: Did you mean you want this SearchOrder:=xlByColumns instead of SearchOrder:=xlByRows
If you won't use "Dim DateStart as Date" maybe you can use "CDate(DateStart)" while comparing.
If you need a specific format you can use (for example):
Format(CDate(DateStart), "dd/mm/yy")

Replace an entire coloumn in excel with a new value automatically

I have VBA code which converts a given specific date format into a normal Date. Is there a way in which I can replace the entire column into my new date format may be by a button click or just using a function.
The code I have is:
Function CONVDATE(myDate) As Date
Dim arr
arr = Split(myDate)
CONVDATE = arr(1) & " " & arr(2) & " " & arr(5) & " " & arr(3)
End Function
Immediately to the right of your data enter:
=TEXT(LEFT(A1,11)&RIGHT(A1,4),"ddd mm dd yyyy")
and double-click the fill handle. Then select, Copy and Paste Special Values over the top.
If you want a VBA solution, and you are happy with your CONVDATE function, you can use something like the following to convert an entire column:
===================================
Option Explicit
Sub CONVALLDATES()
Dim RNG As Range, C As Range
'Next line may change depending on how your range to convert is set up
Set RNG = Range("A1", Cells(Rows.Count, "A").End(xlUp))
'Uncomment next line when debugged.
'application.ScreenUpdating = False
For Each C In RNG
With C
.Value = CONVDATE(C)
'.numberformat = whatever format you want it displayed
End With
Next C
Application.ScreenUpdating = True
End Sub
'---------------------------------------------
Function CONVDATE(myDate) As Date
Dim arr
arr = Split(myDate)
CONVDATE = arr(1) & " " & arr(2) & " " & arr(5) & " " & arr(3)
End Function
====================================
You should add some error checking to ensure the string you are trying to convert is, indeed, in the specific format.

convert numeric to alphanumeric excel cell reference

How can I convert from numeric to alphanumeric cell references? For example, I have the numeric row,col(0,1) and I want to convert to a standard MS Excel alphanumeric col,row(B,1)? I'm sorry, but I don't know the proper terminology to describe different cell references.
I want to write VB.NET code with numeric cell references so my code can iterate but convert to alphanumeric so I can insert formulas into my spreadsheet.
To convert from a numerical column designator to a alphabetic designator, consider:
Sub qwerty()
n = 134
s = Cells(1, n).Address(0, 0)
MsgBox Left(s, Len(s) - 1)
End Sub
EDIT#1:
For a function to perform the conversion:
Public Function ColumnId(N As Long) As String
s = Cells(1, N).Address(0, 0)
ColumnId = Left(s, Len(s) - 1)
End Function
If you want to get the full address. Then you can just use the .Address property of a range.
If you want to separate the row and column then you can split the address into the individual parts using Split on the $.
Sub RangeAddressTest()
Dim cell As Range
Dim fullAddress As String
Dim rowAddress As String, columnAddress As String
Dim detailsArray As Variant
'select your cell
Set cell = ActiveSheet.Cells(30, 25)
fullAddress = cell.Address
detailsArray = Split(fullAddress, "$")
columnAddress = detailsArray(1)
rowAddress = detailsArray(2)
MsgBox "Full Address: " & fullAddress _
& vbCrLf & vbCrLf & _
"Column Address: " & columnAddress _
& vbCrLf & vbCrLf & _
"Row Address: " & rowAddress
End Sub
Thanks for your answers to my question, both seem like they should work but while looking around I found a very simple answer from the Aspose forum that gets the job done with two lines of code. Thanks for your ideas - I learn more by seeing different ways of getting to the same solution.
Aspose Forum:
As per my understanding, you wish to get the cells reference in the syntax of "A1" (Cell Name). You may consider using the following code snippet that returns the alphanumeric cell reference for cell[0,0].
VB
Dim r As Integer = 0, c As Integer = 0
Dim Cell As String = CellsHelper.ColumnIndexToName(c) + (r + 1)

Concatenating Variables Into String to be Set to a Range in VBA

I am having a problem with a particular line of code:
ActiveSheet.Range("A" & rowCount & ":" & Mid(alphabet, totHdrLngth, 1) & belowRowCount)
Where alphabet is a string containing uppercase letters A to Z.
I keep getting the following error:
Run-time error '5':
Invalid Procedure call or argument
I tried creating a String "inRange" and changing the code to this:
inRange = "A" & rowCount & ":" & Mid(alphabet, totHdrLngth, 1) & belowRowCount
curRange = ActiveSheet.Range(inRange)
But that did not help (as I thought it wouldn't). Any suggestions?
Although creating ranges like this is frowned upon in general, the way to do it is with the word SET (like #Gary McGill stated in the comments). Here is an example of how to do this:
Sub test()
Dim alphabet As String
Dim totHrdrLngth As Long
Dim belowRowCount As Long
Dim rowCount As Long
Dim inRange As Range
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
totHrdrLngth = 5
belowRowCount = 10
rowCount = 5
' Gives us A5:E10
Set inRange = Range("A" & rowCount & ":" & range2 & _
Mid$(alphabet, totHrdrLngth, 1) & belowRowCount)
End Sub
You are running this macro in the current range, so there should be no need to specify ActiveSheet.Range. I hope this helps get you toward what you are trying to achieve.
As far as I can tell, you're getting an error because your types don't match up. I imagine rowCount is an integer, as is belowRowCount. If you convert them to strings before concatenating them, you can fix it. str() will convert an integer to a string with a space before it, and LTrim() will remove the space. Try code as below:
Dim sRowCount As String
Dim sBelowRowCount As String
and later
sRowCount = LTrim(Str(RowCount))
sBelowRowCount = LTrim(Str(belowRowCount))
inRange = "A" & sRowCount & ":" & Mid(alphabet, totHdrLngth, 1) & sBelowRowCount
curRange = ActiveSheet.Range(inRange)
Hope this helps.