简体   繁体   中英

Word VBA Convert Long to Short Date

I need to convert this: "Thursday, July 19, 2018" to "7/19/2018". Then convert it to a string so I can replace it with an underscore so I can save the file. I tried cdate, but didn't work. What i tried-> x = cdate(x). Also can someone show me how to do a save prompt

Sub Macro4()
Dim x As String
Dim z As String
Dim y As String

'x has the date
x = ActiveDocument.ContentControls(1).Range.Text
'y has the name
y = ActiveDocument.ContentControls(2).Range.Text
' error with code trying to convert Thursday, July 19, 2018 to 7/19/2018
x = cDate(x,"mm/dd/yyyy")

'replace backslash with an underscore
newstring = Replace(z, "/", "_")

ActiveDocument.SaveAs2 FileName:=z, FileFormat:= _
    wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
    :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
    :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
    SaveAsAOCELetter:=False, CompatibilityMode:=15

End Sub

I think CDate is not the function you're looking for. I believe DateValue would be better. From the language reference:

The required date argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

In any case, having the day of the week in the date is too much - that needs to be cut out. For example:

x = ActiveDocument.ContentControls(1).Range.Text
x = Mid(x, InStr(x, " ") + 1)
'y has the name
y = ActiveDocument.Contentcontrols(2).Range.Text

z = DateValue(x)

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