[英]Excel VBA insert formula with a variable into a cell
我需要使用 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
我試過 Formula 和 FormulaLocal 但結果總是一樣的。
假設出生日期是 6.7.2011。
這意味着,使用您的公式:
.Formula = "=ROUNDDOWN(YEARFRAC(" & dateOfBirth & ",TODAY(),1),0)"
它將創建公式:
=ROUNDDOWN(YEARFRAC(6.7.2011,TODAY(),1),0)
你現在能看到這個問題嗎?
嘗試使用:
.Formula = "=ROUNDDOWN(YEARFRAC(" & dateOfBirth * 1 & ",TODAY(),1),0)"
這將創建公式:
=ROUNDDOWN(YEARFRAC(40730,TODAY(),1),0)
..雖然看起來有點奇怪,但應該給你正確的答案而不是錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.