【问题标题】:Write date to cell and change date format将日期写入单元格并更改日期格式
【发布时间】:2021-01-25 09:19:47
【问题描述】:

我的 VBA 代码有一些问题。我得到了存储为dd/mm/yyyy 的日期变量,但是当我将日期写入特定单元格时,格式更改为mm/dd/yyyy,我尝试了很多选项,但没有一个对我有用,我还检查了变量是否知道是当前的日期、月份和年份。

代码:

Sheets("report_orders").Select
Range("A1").Value = customerName
Range("A2").Value = "äæîðä " & orderID
Range("A3").Value = "äæîðä ì÷åç " & orderPo
'Range("B2").Value = orderDate
Range("B2").Value = Day(orderDate) & "/" & Month(orderDate) & "/" & Year(orderDate)
Debug.Print "year " & Year(orderDate)
Debug.Print "month " & Month(orderDate)
Debug.Print "day " & Day(orderDate)

但结果是:

【问题讨论】:

  • 你可以使用Format()函数。
  • Date variable that stored as dd/mm/yyyy - 它不是这样存储的,因为Date 变量没有格式。您应该删除您的代码并将其替换为Range("B2").Value = orderDate,并且您应该将所需的日期格式应用于单元格。
  • 我都试过了,这些选项都不起作用
  • @lidorag 你试过 BraX 的建议了吗? Range("B2").NumberFormat = "mm/dd/yyyy",然后是 Range("B2").Value = orderDate。它肯定会工作

标签: excel vba


【解决方案1】:

当您将日期放入单元格时,您可以使用.NumberFormat 对其进行格式化。确保在输入值之前格式化单元格。例如

Range("B2").NumberFormat = "mm/dd/yyyy"
Range("B2").Value = orderDate

您可以在Range.NumberFormat property (Excel) 中阅读有关.NumberFormat 的更多信息

【讨论】:

  • 我做了一些改动。如果您不喜欢这些更改,请随时回滚 :)
  • @Gustav。那不是正确的编辑。我已经把它回滚了。在编辑答案之前,请确保您理解 :) 在输入日期之前,必须先对单元格进行格式化。 OP在问题下方的评论中也证实了这一点;)
  • @SiddharthRout:我没有回滚,我更正了它,因为您的陈述是错误的。数字格式可以随时应用。但是我误读了日期格式的请求,抱歉。
  • @SiddharthRout: I didn't roll it back, I corrected it because your statement is wrong. The numberformat can be applied at any time. But I misread the request for the date format, sorry. – Gustav just now @Gustav:我从来没有说过你回滚了 :) 我的陈述也没有错。关于。 .. The numberformat can be applied at any time.我从未质疑过这个事实。你可以随时申请。但要查看效果,您必须在输入日期之前应用它
  • @SiddharthRout:我从未质疑过这个事实。你可以随时申请。但是要看到效果,你必须在输入日期之前应用它。 ...所以你可以,但你不能。使困惑?当然,您可以随时修改格式,显示也会相应改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2021-08-25
  • 2022-07-04
  • 2023-02-03
相关资源
最近更新 更多