使用宏更新会计年度

时间:2016-04-26 05:01:35

标签: vba excel-vba excel

我是VBA for Excel中相对较新的程序员,并在工作相关项目上寻求帮助。

目前的问题是设计预算跟踪系统的更新例程,该系统将更新用户在输入框中指定的任何即将到来的会计年度的日期条目:

Sub Putittogether()
On Error Resume Next

Dim xMonthNumber As Integer
Dim xMonthNumber2 As Integer
Dim xYearInput As Integer
Dim xCell As Range
Dim xCell2 As Range
Dim xMonthYear As Range
Dim xMonthNextYear As Range

Set xMonthYear = Range("B4:B12")
Set xMonthNextYear = Range("B1:B3")


xYearInput = InputBox("Please enter year:")


For Each xCell In xMonthYear
    xCell = xYearInput
        For xMonthNumber = 4 To 12
        Range("B" & xMonthNumber).NumberFormat = "General"
        Range("B" & xMonthNumber) = MonthName(xMonthNumber, True) & xCell
           For Each xCell2 In xMonthNextYear
            xCell2 = xYearInput + 1
                For xMonthNumber2 = 1 To 3
                Range("B" & xMonthNumber2).NumberFormat = "General"
                Range("B" & xMonthNumber2) = MonthName(xMonthNumber2, True) & xCell2
            Next xMonthNumber2
        Next xCell2
    Next xMonthNumber
Next xCell

End Sub

宏从当年4月到次年3月,因此是双循环。

我在两个地方遇到问题:使用我正在使用的方法,B列中的范围需要严格地反映在第1-12行中,而任何其他行都会导致输出问题,我不是确定为什么。

第二个问题是,我每个月都有跟踪总计表,并尝试在具有标题行的表中运行此宏(即将第一个数据行转移到B2)会产生额外的输出问题 - 所以,如何我能让它在不同的范围内工作吗?

提前感谢您的帮助!!

2 个答案:

答案 0 :(得分:1)

可能是您可以使用此代码

Sub Putittogether()
   On Error Resume Next

   Dim xYearInput As Integer
   Dim xColumn As Integer
   Dim xDate As Date

   xYearInput = InputBox("Please enter year:")

   xDate = DateSerial(xYear,4,1)  'you might adjust this date to the first month to be entered

   For xColumn = 1 to 12

        Cells("B" & xColumn ).NumberFormat = "General"
        Cells("B" & xColumn ) = Format(xDate,"MMM YY")
        xDate = DateAdd("m", 1, xDate)

    Next xColumn 

End Sub

答案 1 :(得分:1)

您无法使用Date数据类型,然后使用DateAdd()函数。这会将你的循环简化为两行代码。

如果你需要规定一个起始行,那么一种方法是从startRow到startRow + 11运行行循环。

所以你的代码看起来像这样:

Const START_ROW As Integer = 1 'set this to the row you want
Dim ws As Worksheet
Dim r As Integer
Dim dat As Date
Dim yyyy As Integer

Set ws = ThisWorkbook.Worksheets("Sheet1")

yyyy = InputBox("Please enter year:")

dat = DateSerial(yyyy, 4, 1)
For r = START_ROW To START_ROW + 11
    ws.Cells(r, "B").Value = Format(dat, "mmmyyyy")
    dat = DateAdd("m", 1, dat)
Next