VBA EXCEL formula in a String - excel

Hi I would like to put into a STRING the following formula
Dim stringAppoggio As String
Dim myMonth As String
myMonth = "January 2020"
stringAppoggio="=DAY(EOMONTH(DATEVALUE(01-'&myMonth&'-&YEAR(myMonth)),0))"
It doesn't really give me a syntax error, but I don't see the result of the formula in the String
Thank you

Well, as per my comment, there are a few mistakes here:
You have used single quotes instead of double quotes to seperate your variable from VBA formula syntax
You have forgotten the quotes at all around your second myMonth variable
You have created a formula that simply won't work
Keep in mind, your variable is not just a month but a string holding a month and year > "January 2020", therefor DATEVALUE won't need the 01- and YEAR(myMonth) to work. Let me explain:
=DATEVALUE("January 2020")
Will return Integer 43831, or in other words: 1-1-2020. Then secondly, EOMONTH will return the end of that same month as an Integer, whereas DAY will return the number of that day. So your formula would read:
=DAY(EOMONTH(DATEVALUE("January 2020"),0))
Now to write this in VBA:
Dim stringAppoggio As String
Dim myMonth As String
myMonth = "January 2020"
stringAppoggio = "=DAY(EOMONTH(DATEVALUE(""" & myMonth & """),0))"
You can check that it works:
Debug.Print Evaluate("=DAY(EOMONTH(DATEVALUE(""" & myMonth & """),0))")
Note: See the triple quotes? That's because we need to feed DATEVALUE a string within quotes to work, otherwise it wouldn't be a string and will return an error

Dim stringAppoggio As String
Dim myMonth As String
myMonth = Chr(34) & "January 2020" & Chr(34)
stringAppoggio = "=DAY(EDATE(" & myMonth & ",1)-DAY(" & myMonth & "))"

Related

How to get yyyy-mm-dd from mm/dd/yyy in Excel

I have a date in mm/dd/yyyy format from a textbox in a userform, and I want to get each value mm, dd, and yyyy to a number. (Example, 10/12/2020 would become 2020-10-12)
Here is my code so far, which gets the month part finished.
Dim DateDay As String, DateMonth As String, DateYear As String
Dim firstslash As Integer, secondslash As Integer
firstslash = InStr(TextBox3, "/")
DateMonth = Left(TextBox3, firstslash - 1)
If Len(DateMonth) = 1 Then
DateMonth = "0" & DateMonth
End If
'code for day and year
MsgBox("Date =" & DateYear & "-" & DateMonth & "-" & DateDay)
How can I add to this so it can get the day and year part as well?
The trick is to be sure that you are dealing with a date, that is a large integer (43861 for today). Therefore you should convert whatever is in the textbox to an integer representing a date. That true date you can then present in any format you want. The code below does exactly that.
Private Sub CallExtractDate()
Dim Dat As Date
Dat = ExtractDate("01/31/2020")
MsgBox Format(Dat, "yyyy-mm-dd") & vbCr & _
Format(Dat, "ddd, dd mmm, yyyy") & vbCr & _
Format(Dat, "dddd")
End Sub
Function ExtractDate(ByVal TxtDate As String) As Date
Dim Sp() As String
If IsDate(TxtDate) Then
ExtractDate = CDate(TxtDate)
Else
Sp = Split(TxtDate, "/")
On Error Resume Next
ExtractDate = DateSerial(Int(Sp(2)), Int(Sp(0)), Int(Sp(1)))
End If
End Function
In your project you would probably use the function with a call like this.
Dat = ExtractDate(TextBox1.Value)

function DATE() type mismatch

I can't make this work
Dim StrtD As Long, EndD As Long
Dim StartDate As Date, EndDate As Date
Dim myVar As Variant
Dim stringaAppoggio As String
With ThisWorkbook.Sheets("Settimana")
StartDate = .TextBox1.Value
EndDate = .TextBox2.Value
End With
StrtD = Month(StartDate)
EndD = StrtD + DateDiff("m", StartDate, EndDate)
yearData = year(StartDate)
arr4 = Application.Transpose(.Evaluate("TEXT(DATE(yearData,ROW(" & StrtD & ":" & EndD & "),1), ""[$-0410]mmmm yyyy"")"))
For Each myVar In arr4
stringaAppoggio = myVar
StartDate is "01/01/2020"
EndDate is "01/10/2020"
The error is stringaAppoggio = myVar
type mismatch
I think the error is yearData in Application.Transpose because if I put 2020 it works!
Thank you
yeardata variable is not evaluated passed correctly to your string formula. You need to concatenate it directly into your formula string like what you did in StrtD and EndD variables. Try:
arr4 = Application.Transpose(.Evaluate("TEXT(DATE(" & yearData & _
",ROW(" & StrtD & ":" & EndD & "),1), ""[$-0410]mmmm yyyy"")"))
There are some things going wrong for you here:
Your code should not even compile in the first place, because (with the information you have shown) Application.Transpose(.Evaluate holds a unqualified .Evaluate method.
As I told you yesterday, Debug.Print is a great way of checking if what you intended to write, actually gets written in the .Evaluate. Currently you are using yeardata wrong within the formula. It's a variable holding a string value! Don't get confused with thinking that writing this word within another string automatically picks up you meant to use the variable.
To TRANSPOSE values from a worksheet into a 1D-array, you can do so directly through your formula.
I just assume your code sample above isn't complete and includes a Next below stringaAppoggio = myVar
Considering the above, I think your code can be rewritten to something like:
arr4 = Evaluate("TRANSPOSE(TEXT(DATE(" & yearData & ",ROW(" & StrtD & ":" & EndD & "),1), ""[$-0410]mmmm yyyy""))")

Use of NETWORKDAYS function

I have to find the number of working days between two dates which should exclude weekends and National Holidays.
I am using function NETWORKDAYS in vba, this excludes weekends but I want to exclude Some National Holidays as well.
How to use this function NETWORKDAYS(startDate, endDate, [holidays]) for National holidays. It says it accepts [holidays] as a list. I have all the national holidays in an array. how can I use it with this function via VBA ??
Please find the code snippet.
Public Function dataFromInputSheetHolidayDates() As Variant
Dim holidayDates As Integer
Dim holidaydatesArray(20) As Variant
holidayDates = Sheets("InputSheet").Cells(Rows.Count, "D").End(xlUp).Row
For countDate = 0 To holidayDates - 1
holidaydatesArray(countDate) = Format(Sheets("InputSheet").Cells(countDate + 2, "D").Value, "DD-MMM-YY")
Next countDate
dataFromInputSheetHolidayDates = holidaydatesArray
End Function
holidayList = dataFromInputSheetHolidayDates()
Sheets("Estimation").Range("Z" & taskcounter).Formula = "=NETWORKDAYS(X" &
taskcounter & ",Y" & taskcounter &","& holidayList & ")"
Sheets("Estimation").Range("AB" & taskcounter).Formula = "=NETWORKDAYS(X" &
taskcounter & ",AA" & taskcounter &"," & holidayList & ")"
Change these 2 lines in your code:
Dim holidayDates As Long
holidaydatesArray(countDate) = Sheets("InputSheet").Cells(countDate + 2, "D")
In VBA Integer is up to 32767, which is not quite enough for dates. Furthermore, holidaydatesArray should have a numeric value and not some text format.
Pretty much similar problem as this one - workday holiday argument doesn't accept array
If you are trying to create a flexible formula through VBA, where the holidays are on different worksheet, try this solution:
Public Sub TestMe()
Dim holidayLists As Range
Set holidayLists = Worksheets(2).Range("D1:D10")
With Worksheets(1)
.Range("A1").Formula = "=NETWORKDAYS(B1, C1," & holidayLists.Parent.Name & "!" _
& holidayLists.Address & ")"
End With
End Sub
There the holidayLists.Parent.Name & "!" & holidayLists.Address would refer correctly to the worksheet's name of the holidays.

Formatting a number to two digits even if the first is a 0 vba

I would like to be able to use VBA to display any number between 1-24 as a 2 digit number. Obviously the only ones that have a problem with this are 1-9 which I would like displayed as 01, 02, 03, etc. Is there a way to perform this?
You cannot format an integer variable, you need to use a string variable for formatting.
You can convert the day part of a date to a format with leading zeros using the Day function to extract the day number from the date, and then using the Format function with a "00" format to add a leading zero where necessary
Format(Day(myDate), "00")
myDate is a Date variable containing the full Date value
The following macro can be used as a working sample
Sub Macro1()
Dim myDate As Date
myDate = "2015-5-1"
Dim dayPart As String
dayPart = Format(Day(myDate), "00")
MsgBox dayPart
End Sub
Sure you can format an integer, you just convert it to string within the format command:
formattedIntAsString = Format(Cstr(intValue), "00")
I did it like this:
number_item = 2
number_item = WorksheetFunction.Text(number_item, "00")
This will do the job.
I know it's old, but, to answer the question as clarified, I would use in the built in date formatting functionality.
To modify DeanOC's answer:
Sub Macro1()
Dim dateDate As Date
Dim strDate As String
Dim strDay As String
dateDate = "2015-5-1"
strDate = Format(dateDate, "mm/dd/yy") ' = "05/01/15"
strDay = Format(dateDate, "dd") ' = "01"
MsgBox "The two digit day of """ & strDate & """ is """ & strDay & ""."
End Sub

Convert month name into number

I have dropdown box with months populated. When a month is selected I would like to then convert it to the month number is there a function that can do this?
Eg. September = 9
Another way
Excel Formula
=MONTH(1&A1)
VBA
Sub Sample()
Dim MonthNm As String
MonthNm = "September"
Debug.Print Month(DateValue("01 " & MonthNm & " 2012"))
End Sub
or
Sub Sample()
Dim MonthNm As String
MonthNm = "September"
Debug.Print Application.Evaluate("=MONTH(1&" & Chr(34) & MonthNm & Chr(34) & ")")
End Sub
Replace
Try this...
=MONTH(DATEVALUE(A1&"1"))
Where A1 cell contains month name.
Sub month()
Dim monthh As Integer
monthh = month(Date)
MsgBox monthh
End Sub
try this.
another excel formula where A1 is the cell id with month name:
=TEXT(DATEVALUE(A1&" 1"), "m")
This solution didn't work for me (Excel 2010), I had to shorten the month name to 3 characters and add the day number in front of the shortened string.
=MONTH(1&LEFT(A1;3))
Another VBA solution
For the sake of the art in addition to Siddharth's valid answer :-)
Sub SampleTM()
Dim MonthNm$: MonthNm = "September"
Debug.Print MonthNm2Num(MonthNm)
End Sub
Function MonthNm2Num(ByVal MonthNm) As Long
MonthNm2Num = Format(CDate(MonthNm & "/1 0"), "m") * 1&
End Function

Resources