簡體   English   中英

VBA函數返回月份號

[英]VBA Function that returns the number of the month

我正在嘗試創建一個VBA函數,該函數返回帶有單元格引用的月份數。 我想調用函數CheckMonth

例如,如果我將01/01/2019(dd / mm / yyyy)作為日期,而不是想要將其返回為整數(在這種情況下為01)

或適用於04/06/2019(返回06)12/09/2019(返回09)等

 Function CheckMonth () As integer

  Mid(Range("Active.cell"), 4, 2)

我知道我需要使用這個Mid(range(x,4,2))但不確定如何實現它。

請您提供我該如何做的建議?

如果需要VBA,請考慮:

Function CheckMonth(r As Range) As Integer
    CheckMonth = Month(r.Value)
End Function

無論日期格式如何,它都會返回月份號。

在此處輸入圖片說明

根據之前的注釋,您可以使用“月”功能。 您還需要添加Excel.Range參數:

Function CheckMonth(rngCell As Excel.Range) As Integer
    CheckMonth = Month(rngCell.Value)
End Function

從學習的角度來看,也許有一些選擇可以使您更好地了解可用的各種工具:

Public Function CheckMonth(r As Range) As String
    ' Find month number and then format that to double-digit string
    CheckMonth = Format(Month(r.Value), "00")
End Function

Public Function CheckMonth2(r As Range) As String
    ' Format the date to 'mm' - i.e. just the month element
    CheckMonth2 = Format(r.Value, "mm")
End Function

Public Function CheckMonth3(r As Range) As String
    ' Format the date to a standard string and extract the middle element
    CheckMonth3 = Mid(Format(r.Value, "dd/mm/yyyy"), 4, 2)
End Function

Public Function CheckMonth4(r As Range) As String
    ' Concatenate a zero with the month number, then take last 2 characters
    CheckMonth4 = Right("0" & Month(r.Value), 2)
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM