我有一个Excel电子表格,其中一列列出日期,另一列列出时间。
我的Outlook VBA代码提取日期/时间并将其放入电子邮件中。
[在电子表格中,使用Excel中的“设置单元格格式”功能将其格式设置为“例如下午1:30”。
[如果我只是使用例如从电子表格中提取值的话
.Body = xlSht.Range("A2")
它显示为0.375或“常规”形式的另一个数字。
如果我首先使用此代码格式化时间,
Dim Time1 As Object
Set Time1 = xlSht.Range("B2")
Time1 = Format(Time1, "hh:nn AM/PM")
'[...]
.Body = Time1
它仍然在电子邮件中显示为0.375。
我应该采用其他方法吗?
使用Format$
来应用您的格式:
.Body = Format$(xlSht.Range("B2").Value, "hh:mm AM/PM")
日期时间只是Excel中的数字;在Excel中应用格式不会更改基础值,因此,如果要从单元格中读取值,则需要Format$
。
注意,这个答案是(除BigBen的答案外)是为了解释您的代码为何无法按预期工作:
那么下面的代码实际发生了什么
Dim Time1 As Object
Set Time1 = xlSht.Range("B2")
Time1 = Format(Time1, "hh:nn AM/PM")
.Body = Time1
更确切地说是与…完全相同的文字
Dim Time1 As Object
Set Time1 = xlSht.Range("B2") 'now Time1 is a Range object
Time1.Value = Format(Time1, "hh:nn AM/PM")
.Body = Time1.Value
如果先声明Dim Time1 As Object
,然后再声明Set Time1 = xlSht.Range("B2")
,则Time1
变量是单元格B2的引用。这意味着从现在开始写Time1
实际上与写xlSht.Range("B2")
只是更短![这意味着,如果您现在将该单元格0.375
的值转换为字符串Format(Time1, "hh:nn AM/PM")
,即09:00 AM
,则Time1 = Format(Time1, "hh:nn AM/PM")
将此字符串写回到单元格B2中(由Time1
表示)。它实际上与写作相同:
xlSht.Range("B2") = Format(Time1, "hh:nn AM/PM")
Excel会看到您编写了字符串现在,当Excel开始思考和猜测时,会发生什么情况:
09:00 AM
和thinks: )。“因此它将其转换为一个数字,该数字实际上是0.375
,然后您又回到了开始的位置!现在有两种方法可以解决该问题:Time1 As Object
,但声明为String。 Dim Time1 As String
Time1 = xlSht.Range("B2").Value 'no Set!
因此,行Time1 = Format(Time1, "hh:nn AM/PM")
不会将其写回到单元格中,而只会写回到变量Time1
。
或确保将其写回到单元格时,Excel将其理解为
Text
,并且不会尝试通过将'
作为第一个字符添加来再次尝试将其转换为时间/日期(此不会显示在单元格中):
Dim Time1 As Range 'spcifying it as range instead of object is more precise (a range is an object)
Set Time1 = xlSht.Range("B2")
Time1 = "'" & Format(Time1, "hh:nn AM/PM") 'this will write the date as text into the cell
请注意,强烈建议不要将日期/时间作为文本写到单元格中。您无法再进行计算。因此,我建议第一种选择。