简体   繁体   English

在VBA中将日期和月份更改为DD和MM格式

[英]Changing Day and Month to DD and MM format in VBA

To give some context here, I have a dat file that I am trying to save as an xlsx on my Q drive. 为了提供一些背景信息,我有一个dat文件,试图将其保存为Qlsx文件。 I know that the majority of the code works (I've tested it), so I don't want to completely change it, but the formatting as I explain below is what I need help with. 我知道大多数代码都可以工作(我已经对其进行了测试),所以我不想完全更改它,但是我在下面解释的格式是我需要帮助的。 The following code is in workbook1 and it is referencing workbook2. 以下代码在workbook1中,它引用了workbook2。 Cell D3 in workbook one is a date formula but unfortunately, the FileDay and FileMonth code will only pull in a single "d" or "m" when what I want is it to pull in days and months in the "dd" and "mm" format. 工作簿一中的单元格D3是一个日期公式,但是不幸的是,当FileDay和FileMonth代码只在“ dd”和“ mm”中插入几天和几个月时,它只会插入一个“ d”或“ m”格式。 Since the code below is trying to find a file in this format: "yyyy_mm_dd" but FileDay and FileMonth are only pulling in "d" and "m", it will only work during part of the year. 由于下面的代码正在尝试查找以下格式的文件:“ yyyy_mm_dd”,但是FileDay和FileMonth仅拉入“ d”和“ m”,因此它将仅在一年的一部分时间内工作。 What is the piece of code that I am missing to pull in the correct formatting from cell D3? 我缺少从单元格D3中提取正确格式的代码是什么?

Dim FName As String, FPath As String
Dim wkb1 As Workbook, wkb2 As Workbook

Set wkb1 = ThisWorkbook

FileDay = Day(Range("D3"))
FileMonth = Month(Range("D3"))
FileYear = Year(Range("D3"))


FPath = "Q:\MyFolder"
FName = "MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay & ".xlsx"

Set wkb2 = Workbooks("MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay 
& ".dat")
With wkb2
    .SaveAs Filename:=FPath & "\" & FName
    .Close True
End With
End Sub

Assuming these variables are Strings, use the Format$ function. 假设这些变量是字符串,请使用Format$函数。

FileDay = Format$(Day(Range("D3")), "00")
FileMonth = Format$(Month(Range("D3")), "00")
FileYear = Format$(Year(Range("D3")), "0000")

Alternatively, do it all at once: 或者,一次完成所有操作:

= Format$(Range("D3"), "YYYY_MM_DD")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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