我有一个宏,我在文本框中指定日期(以mm / dd / yyyy为单位),我想以yyyy-mm-dd格式为A列设置此值。我有以下代码:
Sheets("Sheet1").Range("A2", "A50000").Value = TextBox3.Value
Sheet1.Range("A2", "A50000") = Format(Date, "yyyy-mm-dd")
...当我运行宏时,日期仍为mm / dd / yyyy格式。
我如何更改它以使其符合我想要的格式?我一直在尝试通过谷歌研究的多种代码,没有什么能按照我想要的方式设置格式。
任何帮助将不胜感激......
编辑:以下OP评论的完整代码:
Workbooks.Add
Range("A1") = "Acctdate"
Range("B1") = "Ledger"
Range("C1") = "CY"
Range("D1") = "BusinessUnit"
Range("E1") = "OperatingUnit"
Range("F1") = "LOB"
Range("G1") = "Account"
Range("H1") = "TreatyCode"
Range("I1") = "Amount"
Range("J1") = "TransactionCurrency"
Range("K1") = "USDEquivalentAmount"
Range("L1") = "KeyCol"
Sheets("Sheet1").Range("A2", "A50000").Value = TextBox3.Value
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
答案 0 :(得分:32)
使用范围的NumberFormat
属性来强制范围的格式,如下所示:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
答案 1 :(得分:10)
您正在将格式应用于具有代码的工作簿,而不是添加的工作簿。你需要养成完全限定工作表和范围参考的习惯。下面的代码可以在Excel 2010中为我工作:
Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
.Range("A1") = "Acctdate"
.Range("B1") = "Ledger"
.Range("C1") = "CY"
.Range("D1") = "BusinessUnit"
.Range("E1") = "OperatingUnit"
.Range("F1") = "LOB"
.Range("G1") = "Account"
.Range("H1") = "TreatyCode"
.Range("I1") = "Amount"
.Range("J1") = "TransactionCurrency"
.Range("K1") = "USDEquivalentAmount"
.Range("L1") = "KeyCol"
.Range("A2", "A50000").Value = Me.TextBox3.Value
.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub
答案 2 :(得分:1)
当你使用两行时,它可以工作:
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"