简体   繁体   English

添加 NumberFormat 的文本 VBA Excel

[英]Adding Text with the NumberFormat VBA Excel

I have worte below code and now i want to add text with date and Time like this.我写了下面的代码,现在我想像这样添加带有日期和时间的文本。

Last Update on: 3/12/2021  6:38:43 AM

I tried with below code but its not working any help will be appreciated.我尝试使用下面的代码,但它不起作用任何帮助将不胜感激。

With Sheet9.Range("H8")
.Value = Now()
.NumberFormat = "Last update on: " & "mm/dd/yyyy h:mm:ss AM/PM"
End With

The number format in Excel (not VBA) would look like "Last Update on " dd/ mmm yyyy - the fix text needs to be put into quotes. Excel(不是 VBA)中的数字格式看起来像"Last Update on " dd/ mmm yyyy - 修复文本需要放在引号中。

When setting the number format using VBA, you need to tell VBA (not Excel) that you want to have a quote within a string.使用 VBA 设置数字格式时,您需要告诉 VBA(不是 Excel)您希望在字符串中包含引号。 You do this by double the quotes.你可以通过双引号来做到这一点。 Look at the following statement: The first quote tells VBA that a string starts.请看以下语句:第一个引号告诉 VBA 一个字符串开始。 The 2nd and 3rd quote tells VBA that you don't want to end the string but to put a quote character inside the string.第二和第三个引号告诉 VBA 您不想结束字符串,而是在字符串中放置引号字符。

.NumberFormat = """Last Update on "" dd/ mmm yyyy"

"Last update on: " isn't really a valid format. “上次更新时间:”并不是真正有效的格式。
You could try to add the text in after the formatting.您可以尝试在格式化后添加文本。
Usint Range.Text instead of.Value should retain any formatting. Usint Range.Text 而不是.Value 应该保留任何格式。

With Sheet9.Range("H8")
   .Value = Now()
   .NumberFormat = "mm/dd/yyyy h:mm:ss AM/PM"
   .Value = "Last update on: " & .Text
End With

If we are going to have it as a text anyway, we can employ FunThomas method to do it all on one line.如果我们无论如何要将它作为文本,我们可以使用 FunThomas 方法在一行上完成所有操作。

.Value = Format(Now(), """Last update on: "" mm/dd/yyyy h:mm:ss AM/PM")

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

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