简体   繁体   中英

word vba date overflow

I am creating a macro to automate generating invoices. One thing it will do is assign today's date to a formfield in the invoice and calculate the due date by adding days (inserted by the user in a formfield as an integer) to today's date.

I am getting a very basic error on the macro where the following code runs into "error 6: overflow":

dim invDate as Date, dueDate as Date
dim days as Integer
dim invDateFF as Formfield, dueDateFF as Formfield, daysFF as Formfield

set invDateFF = Activedocument.Formfields("Date")
set dueDateFF = Activedocument.Formfields("DueDate")
set daysFF = Activedocument.Formfields("Days")

invDate = Format(Now, "dd/MM/yyyy")
days = daysFF.Result
dueDate = DateAdd("d", days, invDate)
invDateFF.Result = invDate

Both variables (invDate and dueDate) are overflowing...

The formfields are text formfields and they are of a date type. Is there anything obvious I am missing?

Thanks

I've posted this as an Answer because the Comments mechanism is too awkward. It certainly isn't an answer to all the problems you have encountered, but maybe you can use it as a basis for further discussion.

invDate = Format(Now, "dd/MM/yyyy")

The problem is that the result of "Format" is a string, but invDate has Date type. So you are relying on Word to coerce a date in string format into a Date value, which is not a good idea in the general case. Further, I would guess that the main reason you are doing it is to get rid of the time part of the result of the "Now" function. If so, you can use the Date property of VBA.DateTime instead, eg

invDate = Date

or

invDate = VBA.Date

Then the following statements should do the right thing:

days = daysFF.Result
dueDate = DateAdd("d", days, invDate)

But now what you probably want is to plug the result back into your form, which would need

dueDateFF.Result = format(dueDate,"DD/MM/YYYY")

and/or you can use the properties of the FormField to set the format of the date to the one you want to see (and to be accepted - Word has some flexibility in that area).

Personally I would try to focus on getting the code to do what I wanted - the problem you describe with the "days" variable value is certainly a bit weird, but getting to the bottom of that problem may not be required in order to make progress on the form.

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