如何使用VBA在单元格中生成特定格式的随机日期?

时间:2016-01-04 08:48:56

标签: excel vba excel-vba

我的代码如下所示

Dim num As Integer
Dim dblRandBetween  As Double

Dim startDate As Date, endDate As Date
startDate = "1/1/1990"
endDate = "1/1/2012"
num = InputBox("How Many IC numbers need to be generated")

For i = 1 To num
        Set curCell = Worksheets("Sheet1").Cells(i, 3)
    dblRandBetween = WorksheetFunction.RandBetween(startDate, endDate)
    ActiveCell.Value = dblRandBetween
    ActiveCell.Value.NumberFormat = "d/m/yyyy"
    ActiveCell.Offset(1, 0).Activate

Next i

遇到“运行时错误:438”:对象不支持此属性或方法。

1 个答案:

答案 0 :(得分:2)

这是否像改变一样简单:

ActiveCell.Value.NumberFormat = "d/m/yyyy"

ActiveCell.NumberFormat = "d/m/yyyy"

由于numberformat必须应用于活动单元格而不是值。

也许可以尝试完整编辑,如下所示:

Dim num As Integer
Dim dblRandBetween  As Double
Dim startDate As Date, endDate As Date

startDate = "1/1/1990"
endDate = "1/1/2012"
num = InputBox("How Many IC numbers need to be generated")

For i = 1 To num
    dblRandBetween = WorksheetFunction.RandBetween(startDate, endDate)
    With Worksheets("Sheet1").Cells(i, 3)
        .Value = dblRandBetween
        .NumberFormat = "d/m/yyyy"
    End With
Next i