excelvbaexcel-2010

Turn a number into a date in Excel


I need everything in column A to become a date following the number of the sheet.

I have 12 sheets named jan - fev - mar - abr ..... - dez (names of the month in Portuguese).
In sheet "jan" I need everything that is typed in column A to become a date of month 01, like:


Solution

  • Enter the following code into the ThisWorkbook code sheet:

    Note: Code edited to test that worksheet is a Month sheet.

    Option Explicit
    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
        Dim rg As Range, rgInt As Range
        Dim months, monthNum As Long, lastDay As Long, yr As Long
        
    'Change if your abbreviations are different
    months = Array("jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez")
    
    'check that worksheet is a month sheet
        On Error GoTo exitsub
            monthNum = Application.WorksheetFunction.Match(Sh.Name, months, 0)
        ' On Error GoTo 0
        
        Set rgInt = Intersect(Target, Sh.Columns(1))
        If Not rgInt Is Nothing Then
            Application.EnableEvents = False
                yr = Year(Date)
                lastDay = Day(DateSerial(yr, monthNum + 1, 0))
                
    'ensure day number is valid
    
                For Each rg In rgInt
                    If rg.Value >= 1 And rg.Value <= lastDay Then
                        rg.Value = DateSerial(yr, monthNum, rg.Value)
                    Else
                        rg.ClearContents
                    End If
                Next rg
        End If
        
    exitsub:
        Application.EnableEvents = True
    End Sub