VBA Excel - 用于自动填充预算电子表格单元格的简单宏的问题我试图制作

时间:2014-02-13 02:09:09

标签: excel vba date

披露:我对大多数种类的编码缺乏经验,但对其背后的逻辑有一个合理的理解,而且通常只需要一点点推动语法正确等等。

我要做的是创建一个电子表格,其中顶行是连续日期的列表。在前几列是账单等数据。我希望我的宏做的是查看账单金额,开始和结束日期以及账单的频率(每周/每月等),然后填写单元格账单到期日期列中的同一行。我花了最后一天提出这段代码,直到我去运行它,我才非常满意。我已经摆脱了一些我正在使用变量的错误。值显然不存在但是现在我遇到了一些我不能掌握的问题。我没有运气搜索互联网。

调试找到的第一个问题是在这一行:

currentDate = Cells(G, currentRow).Value 'Set Start Date

我遇到运行时错误'1004':应用程序定义或对象定义错误。我确信这只是一个简单的语法问题。该行应该做什么(在第一个实例中)正在查看单元格“G3”中的开始日期,该日期被格式化为日期(04-Feb-14)并分配变量currentDate到那个日期,这样我就可以在第一行的所有日期中搜索'currentDate'。

我是否足够清楚?我的代码如下。

我的代码:

Private Sub CommandButton1_Click()
   Dim currentDate As Date
   Dim currentRow As Integer
   Dim repeatuntilDate As Date
   Dim repeatuntilRow 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(G, currentRow).Value 'Set Start Date
   repeatuntilDate = Cells("H,currentRow").Value 'Set End Date
       While currentDate <= repeatuntilDate 'Loop from Start Date until End Date
       dateAddress = Range("J1:AAI1").Find(currentDate, LookIn:=xlValues).Address 'find the current date within the range of dates in row 1
       Cells("dateAddress.Column,currentRow").Value = Cells("D,currentRow").Value 'Populate cell with amount
       'Increment the currentDate by the chosen frequency
       If Cells("E,currentRow").Value = "Weekly" Then
           currentDate = DateAdd("ww", 1, currentDate)
       ElseIf Cells("E,currentRow").Value = "Fortnightly" Then
           currentDate = DateAdd("ww", 2, currentDate)
       ElseIf Cells("E,currentRow").Value = "Monthly" Then
           currentDate = DateAdd("m", 1, currentDate)
       ElseIf Cells("E,currentRow").Value = "Quarterly" Then
           currentDate = DateAdd("q", 1, currentDatee)
       ElseIf Cells("E,currentRow").Value = "6 Monthly" Then
           currentDate = DateAdd("m", 6, currentDate)
       ElseIf Cells("E,currentRow").Value = "Annually" Then
           currentDate = DateAdd("y", 1, currentDate)
       ' ElseIf Cells("E,currentRow").Value = "Once off" Then
           ' Exit While
       End If
       Wend
   currentRow = currentRow + 1 'Once row is complete, increment to next row down
   Wend
End Sub

1 个答案:

答案 0 :(得分:2)

回答为什么Object Defined Error错过了Cells属性语法:

Cells(row_index, col_index)接受long数据类型(数字)。

所以它应该是:

currentDate = Cells(currentRow, 7).Value 'G is the 7th column

但同样地,您可以像这样引用col_index参数:

currentDate = Cells(currentRow, "G").Value 'take note of the qoutation marks ""