2012年4月19日 星期四

Excel 自動編號功能實現

人工作業表單用人的腦筋去記編號常會發生錯亂的情況,

此時只好請出VBA了。

 

作業步驟:

1.建立一個button改名為"取得單據編號”

2.按<Alt>+F11進到VBA的IDE

3.新增模組

 

新增程式碼如下:

Private oExcel As Object
Private oBook As Object
Private OSheet As Object
Private cno As String

'Green 2012/04/19
'產生的編碼方式是"M7"+"年月"+"排序",如M7201204001........
'value 取儲存格實際值,text取顯示值(唯讀)

Function 取得單據編號_Click()
    Set OSheet = Worksheets("單據號碼")
 
   '取得A2資料之最後一列(非空白)
    lastrow = OSheet.Range("A1").End(xlDown)
    If lastrow = 0 Or lastrow = "" Then
        lastrow = 1
    End If
    Set mcell = OSheet.Cells(lastrow, 1)
    If Val(mcell.Value) = 0 Then
        cno = "1"
        mcell.Value = 1
       
'記錄時間
        OSheet.Cells(lastrow, 2).Value = Date
        OSheet.Cells(lastrow, 3).Value = Time()
    Else
       
'檢查記錄的時間年月是否跨年月
        If Year(OSheet.Cells(lastrow, 2).Value) <> Year(Date) Or Month(OSheet.Cells(lastrow, 2).Value) <> Month(Date) Then
            MsgBox "已跨月,編號將會重編!!"
            OSheet.Cells.Delete
            Set mcell = OSheet.Cells(1, 1)
            lastrow = 0
        End If
        cno = Str(Val(mcell.Value) + 1)
        Set mcell = OSheet.Cells(lastrow + 1, 1)
        mcell.Value = Val(cno)
        '記錄時間
        OSheet.Cells(lastrow + 1, 2).Value = Date
        OSheet.Cells(lastrow + 1, 3).Value = Time()
    End If
   
'依編碼方式取得序號
    reqno = "M7" & Year(Date) & Right("00" & Trim(Month(Date)), 2) & Right("000" + Trim(cno), 3)
    Set OSheet = Worksheets("F5")
    OSheet.Range("J3") = reqno
    OSheet.Range("B8:L20").Value = "" '清除之前填表的內容
    OSheet.Range("B8").Select
End Function

程式碼說明:

本檔案有兩個工作表(Sheet):

F5 – 要填寫的表單工作表

單據號碼 - 記錄自動編號之序號及日期時間 ,本工作表可以設隱藏;以免使用者誤動資料

 

關鍵儲存格:

J3 - 填寫表單單據編號之儲存格

沒有留言: