发票计数器引用上一个工作表单元格

时间:2018-04-20 18:43:31

标签: excel vba excel-vba

我需要在60个工作表的工作簿上按顺序生成发票编号的代码。当前的工作簿设置了封面页,其中包含" 0000"在单元格D3中。目标是让代码循环遍历所有工作表,并根据前一个工作表(0001,0002,0003,...)按顺序将下一个数字输入到单元格D3中。

我目前正在处理下面的代码,一半是我的创作,另一半是我在参考之前的工作表时所做的研究。

Sub InvoiceCounter()

Dim sh As Worksheet
Dim i As Integer

Application.Volatile

    For Each sh In Worksheets
        If IsEmpty(Range("D3").Value) = True Then
            i = rCell.Cells(1).Parent.Index
            PrevSheet(D3 + 1) = Sheets(i - 1).Range(rCell.Address)
        End If
    Next sh

End Sub

我使用"如果是IsEmpty"是这样,代码会跳过封面页,封面总是有一个值(这将根据发票类型手动输入)。

任何建议或贡献表示赞赏。

谢谢,

肖恩

1 个答案:

答案 0 :(得分:0)

尝试下面的版本

Option Explicit

Public Sub InvoiceCounter1()    'If cover page is the first Tab (leftmost)
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If Not ws.Previous Is Nothing Then         'Or If ws.Name <> "Coveer Page" Then
            ws.Range("D3").Value2 = Val(ws.Previous.Range("D3").Value2) + 1
            ws.Range("D3").NumberFormat = "0000"
        End If
    Next
End Sub
Public Sub InvoiceCounter2()    'If cover page is after other Tabs
    Dim ws As Worksheet, tabID As Long

    For Each ws In ThisWorkbook.Worksheets
        If ws.Range("D3").Value2 <> "0000" Then    'If Len(ws.Range("D3").Value2) = 0 Then
            tabID = tabID + 1
            ws.Range("D3").Value2 = tabID          'Or ws.Index - 1 vs ws.Index - 2
            ws.Range("D3").NumberFormat = "0000"
        End If
    Next
End Sub
Public Sub InvoiceCounter3()    'If cover page is the first Tab (leftmost)
    Worksheets.Select
    Range("D3").Select
    Selection.Formula = "=wsID()"
    Selection.NumberFormat = "0000"
End Sub

Public Sub InvoiceCounter4()    'If cover page is the first Tab (leftmost)
    Worksheets.Select
    Range("D3").Select
    Selection.Formula = "=wsID()"
    ActiveWindow.SelectedSheets.FillAcrossSheets Range:=Selection, Type:=xlAll
    Selection.NumberFormat = "0000"
End Sub

Public Function wsID() As Long
    If IsObject(Application.Caller) Then wsID = Application.Caller.Parent.Index - 1
End Function