在 Excel 中将数字转换为日期

问题描述 投票:0回答:1

我需要 A 列中的所有内容都成为工作表编号后面的日期。

我有 12 张纸,名为 jan - fev - mar - abr ..... - dez (葡萄牙语月份名称)。
在工作表“jan”中,我需要在 A 列中输入的所有内容都成为 01 月的日期,例如:

  • 如果我在单元格 A15 中输入 5,则会变为 05/01/2024(日/月/年)。
  • 如果我在工作表“abr”(四月)的单元格 A17 中输入 12,它将变为 12/04/2024。
excel vba excel-2010
1个回答
2
投票

ThisWorkbook
代码表中输入以下代码:

注意:编辑代码以测试该工作表是Month工作表。

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
© www.soinside.com 2019 - 2024. All rights reserved.