Hi,
I did notice that in Nigel's code. One way around it would be to check
if the file is the template or not. Here's my take on it, solving that
problem and using a document property:
Private Sub Workbook_Open()
Dim InvNo As Long, InvPath As String, PathDepth As Integer
Dim PartPath As String, i As Integer
If Len(ThisWorkbook.Path) > 0 Then Exit Sub
On Error Resume Next
InvPath = "C:\Documents\Invoices\2008"
PathDepth = Len(InvPath) - Len(Replace(InvPath, "\", ""))
i = PathDepth - 2
Do Until Len(Dir(InvPath, vbDirectory)) > 0
If i > -1 Then
PartPath = StrReverse(Replace(StrReverse(InvPath), "\",
"", , i))
MkDir Left(PartPath, InStrRev(PartPath, "\") - 1)
i = i - 1
Else
MkDir InvPath
End If
Loop
InvNo = Int(Mid(ThisWorkbook.BuiltinDocumentProperties("Title"),
9)) + 1
If InvNo = 0 Then InvNo = 1
With ThisWorkbook
.BuiltinDocumentProperties("Title") = "Invoice " &
Format(InvNo, "00000")
.SaveCopyAs InvPath & "\Template.xlt"
.SaveAs Filename:=InvPath & "\Invoice " & Format(InvNo,
"00000") & ".xls"
End With
End Sub
Note the third line that simply checks the path of the file. If you
have opened the template, the file has not yet been saved, hence the
path is zero length.
As for using the document property, I prefer this method as it exposes
the data to Windows etc. If you hover the mouse over the file in
explorer for example, in this case it will show the invoice number. To
display the number in a cell in the worksheet, you can either add a
line of code that sets it when the file is created, " Range("A1") =
InvNo " for example, or add the following code to a module in the
template:
Function Invoice()
Invoice = Int(Mid(ThisWorkbook.BuiltinDocumentProperties("Title"),
9))
End Function
Then you can simply put the formula " =Invoice() " anywhere in the
file and it will contain the correct number and never be out of sync
with the file.
Cheers,
Ivan.