簡體   English   中英

在excel VBA中的函數內更改單元格格式

[英]change cell format within functions in excel VBA

我在excel vba中編寫了一個函數。 函數的返回值是日期,但是函數只是返回單元格中日期的值

如何更改單元格的格式為日期(首選短日期)

這是我的代碼

Function ggg(rng As Range) As Date
ggg = rng.value - 466699
ggg = CDate(ggg)
End Function

您不能使用該功能更改單元格的格式。 您需要返回字符串的子例程或函數。 例如:

Function ggg(rng As Range) As String
    ggg = Format(rng.Value, "yyyy-mm-dd")
End Function

右鍵單擊工作表標簽,然后選擇“查看代碼”。 粘貼下面提供的代碼。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cel As Range
    For Each cel In Target.Cells
        If cel.HasFormula And (InStr(1, cel.Formula, "=ggg(", vbTextCompare) = 1) Then
            cel.NumberFormat = "dd-mm-yyyy"
        End If
    Next cel
End Sub

並查看它是否對您的事業有所幫助!

暫無
暫無

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

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