用户定义函数返回Excel VBA中不可格式化的日期

用户定义函数返回Excel VBA中不可格式化的日期,vba,excel,Vba,Excel,我在ExcelVBA中创建了一个UDF,它返回日期和双精度的多维数组。问题是我无法格式化返回的日期 以下是一个简化的示例: Function test(dates as Range) Dim results Dim i As Integer ReDim results(1 To dates.Cells.Count) For i = 1 To dates.Cells.Count results(i) = dates.Cells(i).Value

我在ExcelVBA中创建了一个UDF,它返回日期和双精度的多维数组。问题是我无法格式化返回的日期

以下是一个简化的示例:

Function test(dates as Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function
末尾的转置只是为了方便列输出(我按Ctrl+Shift+enter)。如果您使用这个简化的示例,您将无法格式化输出,并且严格意义上不会将其视为日期


有什么想法吗?

将结果数组更改为双倍:

Function test(dates As Range)
    Dim results() As Double
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function
或者将
dates.Cells(i).Value更改为
dates.Cells(i).Value2
,它将返回双精度而不是日期字符串:

Function test(dates As Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value2
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function

然后根据需要格式化单元格。

您可以尝试以下方法

Results(i) = CDate(dates.Cells(i).Value)

您的代码对我来说很好,只需确保输出单元格的格式为日期或General@CallumDA对我来说,它返回的字符串不能为空reformatted@ScottCraner:哦,我明白了……好的,谢谢。我使用了Value2,它解决了我的问题!