我試圖從主excel文件中抓取數據,將零件複製到新文件中,並將日期保存爲字符串中的日期文件名,格式dd.mm.yyyy但我不能得到日期轉換爲字符串,以便在文件名中使用它。非常感謝。我在網上找到了一大堆解決方案,但沒有一個適合我。非常感謝。vba將日期dd.mm.yyyy轉換爲字符串以便在文件名中使用
Sub invoicing()
Dim invoiceno As Variant 'but when grabbed from the file, it's string
Dim tourdate As Date
Dim final As String
Dim tourdate2 As String
Dim startrow As Variant
Dim endrow As Variant
startrow = 98
endrow = 170
Dim templatefilename As String
Dim newfilename As Variant
Dim oWorkbook As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim destinationpath As String
destinationpath = CurDir
templatefilename = "Template Invoice.xlsx"
Set oWorkbook = Workbooks.Open(destinationpath & Application.PathSeparator &templatefilename)
oWorkbook.Activate
Set ws1 = oWorkbook.ActiveSheet
Set ws2 = ThisWorkbook.Sheets("2015 client details")
With ws1
.Cells(10, 3).Value = ws2.Cells(startrow, 16).Value 'invoice number
.Cells(9, 3).Value = ws2.Cells(startrow, 25).Value 'enquiry date
.Cells(11, 3).Value = ws2.Cells(startrow, 9).Value 'first name and last name
.Cells(12, 3).Value = ws2.Cells(startrow, 30).Value 'pay date
.Cells(12, 4).Value = ws2.Cells(startrow, 18).Value 'pay method
.Cells(17, 2).Value = ws2.Cells(startrow, 12).Value '# Adults, # Children, (Private)
.Cells(17, 2).RowHeight = 50
.Cells(17, 2).EntireRow.AutoFit
.Cells(17, 3).Value = ws2.Cells(startrow, 23).Value 'tour date
.Cells(17, 4).Value = ws2.Cells(startrow, 17).Value 'Amount
.Cells(17, 5).Value = ws2.Cells(startrow, 17).Value 'Total Amount
End With
invoiceno = ws1.Cells(10, 3).Value
tourdate = ws1.Cells(17, 3).Value 'as date which cannot be used in file name in this form
tourdate2 = Format(tourdate, "dd.mm.yyyy")
'tourdate.Value = tourdate.Text
'tourdate.NumberFormat = "@"
newfilename = "Invoice" & " " & invoiceno & tourdate2
final = destinationpath & Application.PathSeparator & newfilename & tourdate
oWorkbook.SaveAs final, xlOpenXMLWorkbook
oWorkbook.Close
End Sub
我覺得你的問題是,你想保存多點的工作文件''在文件名中。有些操作系統允許這樣做,但Windows已經很難(根據我的經驗)。作爲一個長期習慣,我使用下劃線。所以'newfilename =「Invoice」&「」&invoiceno&「_」&Format(tourdate,「dd_mm_yyyy」)'應該適合你。 – PeterT