Arie Bos
Board Regular
- Joined
- Mar 25, 2016
- Messages
- 224
- Office Version
- 365
- Platform
- Windows
I have a main folder ('...\Sales\PO') with a series of project folders, named 2023.001 - xxxx, 2023.002 - yyyy, 2023.003 - zzzz and so forth.
I want to place the last number found + 1 in a cell, so that should be 2023.004.
the following code is working well, but it returns 2023.3004. I can't find why this is though.
I want to place the last number found + 1 in a cell, so that should be 2023.004.
the following code is working well, but it returns 2023.3004. I can't find why this is though.
VBA Code:
Sub CreateNewProjectNumber()
Dim fso As Object
Dim folder As Object
Dim folderName As String
Dim folderNumber As Double
Dim maxNumber As Double
Dim folderPath As String
Dim currentYear As Integer
' Get the current year
currentYear = Year(Date)
' Set the folder path where the folders are located
folderPath = Environ("userprofile") & "\OneDrive - ADAR Technologies, LLC\SharePoint\Sales\PO\"
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Loop through the folders in the specified directory
For Each folder In fso.GetFolder(folderPath).SubFolders
' Check if the folder name matches the pattern
If folder.Name Like currentYear & ".* - *" Then
' Extract the folder number from the folder name
folderNumber = CDbl(Mid(folder.Name, Len(currentYear) + 2, InStr(folder.Name, " ") - Len(currentYear) - 2))
' Update the maximum number if the current number is larger
If folderNumber > maxNumber Then
maxNumber = folderNumber
End If
End If
Next folder
' Add 1 to the maximum number
maxNumber = maxNumber + 1
' Determine the number of leading zeros needed
Dim leadingZeros As String
leadingZeros = IIf(maxNumber < 10, "00", IIf(maxNumber < 100, "0", ""))
' Assign the result to the 'Project.Num' cell as a string
Worksheets("Quotation").Range("Project.Num").NumberFormat = "@"
Worksheets("Quotation").Range("Project.Num").Value = currentYear & "." & leadingZeros & maxNumber
Worksheets("Quotation").Range("Project.Num").NumberFormat = "0000\.000"
End Sub