简体   繁体   中英

Excel - Writing to text file with Format(date)

I have a code that can create and write text file. Below is the code:

Public Sub createFil()


Dim fso As Object
Dim datetext As String

Const FLDR_NAME As String = "C:\testing"

Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateFolder (FLDR_NAME)

Dim Fileout1 As Object

Set Fileout1 = fso.CreateTextFile("C:\testing\test.txt", True, False)
datetext = Worksheets("Sheet1").Range("C2").Value & Worksheets("Sheet1").Range("F2").Value & "Hello World"
Fileout1.Write datetext
Fileout1.Close

End Sub

As you can see, C2 value is "HI" and F2 value is current date which is "=today()".

At the result file, the date format i get is "2/15/2017". but the format that I want is "02/15/17".

I have changed the format at Excel sheet for the F2. Am i missing something here?

Thank you.

You can format the date in VBA before outputting it:

datetext = Worksheets("Sheet1").Range("C2").Value & _ 
    Format(Worksheets("Sheet1").Range("F2").Value, "mm/dd/yyyy") & _ 
    "Hello World"

Try this after Dim Fileout1 As Object

With Worksheets("Sheet1").Range("F2")
    .NumberFormat = "mm/dd/yy;@"
End With

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