简体   繁体   中英

VBA EXCEL formula in a String

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 & "))"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM