VBA Excel – 运行时错误'1004'当试图分配一个单元格的值

对于背景,请参阅我以前的问题 。 ((我之前发布了相同的代码,但是有不同的问题,但这是我遇到的一个新问题。)

我已经摆脱了使用variables的一些错误.Value已经搞乱了Cells(row,column)的语法,而且我刚刚修复了.Find所以我现在正确地使用它。

我以为我只是在那里完成这个代码,但现在我收到一个运行时错误'1004':应用程序定义或对象定义的错误消息在这一行:

 Cells(currentRow, dateAddress).Value = billAmount 'Cells(currentRow, "D").Value 'Populate cell with amount 

我曾尝试使用Set 。 我已经尝试创build一个variablesbillAmount ,从Cells(currentRow, "D").Value赋值给它,然后像上面那样赋值Cells(currentRow, dateAddress).Value

我已经尝试只有一个单元格等于其他单元Cells(currentRow, dateAddress).Value = Cells(currentRow, "D").Value单元Cells(currentRow, dateAddress).Value = Cells(currentRow, "D").Value但也不起作用。

在debugging模式下,如果我将鼠标hover在currentRowbillAmountdateAddress它们都具有期望的值。 然而,我似乎无法得到最后的细胞填充。 一旦我解决了这个问题,我相信我必须将其应用于我的代码的最后部分中的所有IF THEN语句。 但希望那么它应该是完整的。

这是我的代码:

 Private Sub CommandButton1_Click() Dim currentDate As Date Dim currentRow As Integer Dim repeatuntilDate As Date Dim repeatuntilRow As Integer Dim dateAddress As String Dim dateRange As Range Dim lastDate As Range Dim billAmount As Integer currentRow = 3 'First row of entries repeatuntilRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'Last row of entries While currentRow < repeatuntilRow 'Loop from first row until last row of entries currentDate = Cells(currentRow, "G").Value 'Set Start Date repeatuntilDate = Cells(currentRow, "H").Value 'Set End Date billAmount = Cells(currentRow, "D").Value While currentDate <= repeatuntilDate 'Loop from Start Date until End Date With Range("J1:AAI1") Set lastDate = .Cells(.Cells.Count) 'Setup for the upcoming Find to begin at the lastDate End With Set dateRange = Range("J1:AAI1").Find(What:=currentDate, After:=lastDate) dateAddress = dateRange.Column 'Obtain column of the found Date Cells(currentRow, dateAddress).Value = billAmount 'Cells(currentRow, "D").Value 'Populate cell with amount 'Increment the currentDate by the chosen frequency If Cells(currentRow, "E").Value = "Weekly" Then currentDate = DateAdd("ww", 1, currentDate) ElseIf Cells(currentRow, "E").Value = "Fortnightly" Then currentDate = DateAdd("ww", 2, currentDate) ElseIf Cells(currentRow, "E").Value = "Monthly" Then currentDate = DateAdd("m", 1, currentDate) ElseIf Cells(currentRow, "E").Value = "Quarterly" Then currentDate = DateAdd("q", 1, currentDatee) ElseIf Cells(currentRow, "E").Value = "6 Monthly" Then currentDate = DateAdd("m", 6, currentDate) ElseIf Cells(currentRow, "E").Value = "Annually" Then currentDate = DateAdd("y", 1, currentDate) ' ElseIf Cells(currentRow,"E").Value = "Once off" Then ' Exit While End If Wend currentRow = currentRow + 1 'Once row is complete, increment to next row down Wend End Sub 

在此之前:

 Cells(currentRow, dateAddress).Value = billAmount 

声明你的dateAddressvariables是一个整数,因为它包含一个整数,而带有dateAddress Cells(currentRow, dateAddresse)作为包含一个数字的String将抛出Run-time Error 1004

 Dim dateAddress as Integer 

最后一件事,我build议你把dateAddress dateCol或者其他东西,这样对于其他人甚至是你来说,如果你在编写代码之后重新检查一下你的代码,它就更加清晰了。