Excel VBA将带有变量的公式插入单元格

Excel VBA将带有变量的公式插入单元格,excel,vba,excel-formula,Excel,Vba,Excel Formula,我需要在单元格中插入使用VBA的公式,但我总是遇到运行时错误1004。代码如下所示: Sub save_data() Dim source As Worksheet Dim list As Worksheet Dim nextRow As Integer Dim nextId As Integer Dim startDate As Date, endDate As Date, randDatum As Date, dateOfBirth As Date startDate = "17/6/2

我需要在单元格中插入使用VBA的公式,但我总是遇到运行时错误1004。代码如下所示:

Sub save_data()

Dim source As Worksheet
Dim list As Worksheet
Dim nextRow As Integer
Dim nextId As Integer
Dim startDate As Date, endDate As Date, randDatum As Date, dateOfBirth As Date

startDate = "17/6/2018"
randDate = WorksheetFunction.RandBetween(startDate, Date)

Set source = Worksheets("Add user")
Set list = Worksheets("Users")

nextRow = list.Range("A" & list.Rows.Count).End(xlUp).Offset(1).Row
nextId = list.Range("A" & list.Rows.Count).End(xlUp).Value + 1
dateOfBirth = source.Range("F24").Value

list.Cells(nextRow, 1).Value = nextId
list.Cells(nextRow, 2).Value = source.Range("F4").Value
list.Cells(nextRow, 3).Value = source.Range("F6").Value
list.Cells(nextRow, 4).Value = source.Range("F8").Value
list.Cells(nextRow, 5).Value = source.Range("F10").Value
list.Cells(nextRow, 6).Value = source.Range("F12").Value
list.Cells(nextRow, 7).Value = source.Range("F14").Value
list.Cells(nextRow, 8).Value = source.Range("F16").Value
list.Cells(nextRow, 9).Value = source.Range("F18").Value
list.Cells(nextRow, 10).Value = source.Range("F20").Value
list.Cells(nextRow, 11).Value = source.Range("F22").Value
list.Cells(nextRow, 12).Value = source.Range("F24").Value
list.Range("M" & nextRow).Formula = "=ROUNDDOWN(YEARFRAC(" & dateOfBirth & ",TODAY(),1),0)"
list.Cells(nextRow, 14).Value = Date
list.Cells(nextRow, 15).Value = randDate
list.Cells(nextRow, 16).Value = Date - randDate
list.Cells(nextRow, 16).Value = "=TODAY()"

End Sub

我试过配方奶粉和配方奶粉,但结果总是一样的。

假设出生日期是2011年7月6日

这意味着,使用您的公式:

.Formula=“=ROUNDDOWN(YEARFRAC(&dateOfBirth&)”,TODAY(),1),0)”

它将创建以下公式:

=汇总(YEARFRAC(6.7.2011,TODAY(),1),0)

你现在能看到问题了吗

尝试使用:

.Formula=“=ROUNDDOWN(YEARFRAC(&dateOfBirth*1&”,TODAY(),1),0)”

这将创建以下公式:

=ROUNDDOWN(YEARFRAC(40730,TODAY(),1),0)


…虽然看起来有点奇怪,但应该给您正确的答案,而不是错误。

当您在这一行中断代码时,
dateOfBirth
变量的值是多少?什么是“永远不变”的“结果”?错误?意外的回答?还有什么?您是否正确设置了
source
list
?出生日期的值为2011年7月6日。结果是我总是得到运行时错误。是的,源代码和列表设置正确,在代码的其他部分也有效。我将分号改为逗号,公式有效。我们需要查看完整的代码。你的配方看起来不错。也许
nextrow
中填充了一个值1048576。只能用这个部分代码猜测