在Excel VBA中抵消变通方法

时间:2016-10-19 06:41:26

标签: excel vba excel-vba accounting

我正在尝试自动将会计日记帐分录过帐到分类帐,并且在添加新行后我正在努力抵消。我的工作簿有两个表,即Journal和Ledger,我的目标是读取每个日记帐分录,并通过添加新行将条目添加到分类帐中的正确T帐户。大多数复制条目都有效,但一旦偏移发生变化,宏就会遇到问题。我正在考虑使用.Find作为更好的选择,因为不同的T帐户需要不同的抵消价值,具体取决于先前帐户的数量。如何解决此偏移行问题?

以下是Excel File的链接,下面是我在VBA中的代码。

Sub RowInsert()

Dim offset As Integer
offset = 0

Dim counter As Integer
For counter = 0 To 1

Dim account As String
account = Worksheets("Journal").Cells(counter + 2, 2)


Dim a As Double

If Worksheets("Journal").Cells(counter + 2, 2) = "Cash" Then
Worksheets("Ledger").Rows(4 + offset).Insert Shift:=xlDown

offset = offset + 1

Worksheets("Ledger").Cells(6 + offset, 1).Value = Worksheets("Journal").Cells(counter + 2, 1).Value

    If Worksheets("Journal").Cells(counter + 2, 3).Value = Null Then
    Worksheets("Ledger").Cells(6 + offset, 3).Value = Worksheets("Journal").Cells(counter + 2, 4).Value
    Else
    Worksheets("Ledger").Cells(6 + offset, 2).Value = Worksheets("Journal").Cells(counter + 2, 3).Value
    End If

ElseIf Worksheets("Journal").Cells(counter + 2, 2) = "Equipment" Then
Worksheets("Ledger").Rows(8 + offset).Insert Shift:=xlDown

offset = offset + 1

Worksheets("Ledger").Cells(6 + offset, 1).Value = Worksheets("Journal").Cells(counter + 2, 1).Value

    If Worksheets("Journal").Cells(counter + 2, 3).Value = Null Then
    Worksheets("Ledger").Cells(6 + offset, 3).Value = Worksheets("Journal").Cells(counter + 2, 4).Value
    Else
    Worksheets("Ledger").Cells(6 + offset, 2).Value = Worksheets("Journal").Cells(counter + 2, 3).Value
    End If

End If
Next counter
End Sub

EDIT。如果我要追求Range.Find解决方案,我该如何访问此范围/单元格结果?现在我得到"运行时错误' 91':对象变量或者没有设置块变量"。

Sub RowInsert()

Dim counter As Integer
For counter = 0 To 1

Dim account As String
account = Worksheets("Journal").Cells(counter + 2, 2)


Dim a As Double

If Worksheets("Journal").Cells(counter + 2, 2) = "Cash" Then

    Dim entries As Integer
    entries = 0
    Dim Header As Range
    Dim row As Long

    With Worksheets("Ledger").Range("a1:a100")

        Set Header = .Find("Cash")
        ` Error here when try to use the Range Header
        row = Header.row + entries

        Rows(row).Insert Shift:=xlDown

        Cells(row, 1) = Worksheets("Journal").Cells(counter + 2, 1).Value

    End With

End If
Next counter

End Sub

1 个答案:

答案 0 :(得分:0)

回答您编辑过的问题:

您收到的错误是因为.Find未找到任何内容并返回Nothing。尝试访问Nothing的属性将导致“对象变量或未设置块变量”错误。

.Find不能很好地处理合并的单元格。在您的情况下,简单的解决方案是扩展搜索范围,使其包含整个合并单元格。

Dim Header As Range
Dim lastRow As Long

With Worksheets("Ledger").Columns("A:C")

    Set Header = .Find("Cash")
    lastRow = Header.Row + entries
    'I would prefer something like
    'lastRow = Worksheets("Ledger").Cells(Header.Row, "B").End(xlDown).Row (not tested)

    Rows(lastRow).Insert Shift:=xlDown

    Worksheets("Ledger").Cells(lastRow, 1) = Worksheets("Journal").Cells(counter + 2, 1).Value
End With

我更改了行变量的名称,因此属性Row和变量row之间没有混淆。您可以看到VBE已经混淆了,因为它将属性设置为小写。