如何在VBA中显示返回的mystring值作为日期

时间:2017-07-12 08:33:37

标签: excel vba excel-vba

我创建了一个功能,根据我的考勤表中的缺席条目来缺席。

我的代码是:

Dim cell As Range
Dim myString As String

'Loop through all the cells in the range
For Each cell In myRange
    'Check for value
    If cell = "A" Then
        myString = myString & Cells(myRow, cell.Column) & ", "
    End If
Next cell

'Return string
If Len(myString) > 0 Then
    AbsentDays = Left(myString, Len(myString) - 2)
End If

End Function

我想显示显示为"dd mmm"的返回值。

2 个答案:

答案 0 :(得分:1)

我假设AbsentDaysString,而您6/7/2017, 6/9/2017, 6/15/2017, 6/16/2017String(而不是Date)。

请尝试以下String转换代码:

Dim AbsentDays  As String
Dim DatesArr As Variant
Dim i As Long

' for my tests
AbsentDays = "6/7/2017, 6/9/2017, 6/15/2017, 6/16/2017"

' use the split to get the values in an array
DatesArr = Split(AbsentDays, ",")
Dim myDateformat As Variant

' loop through array
For i = 0 To UBound(DatesArr)
    If i = 0 Then ' first array element
        myDateformat = Format(CDate(DatesArr(i)), "dd mmm")
    Else ' 2nd array element and above
        myDateformat = myDateformat & ", " & Format(CDate(DatesArr(i)), "dd mmm")
    End If
Next i

MsgBox myDateformat

答案 1 :(得分:1)

仅仅因为我希望将更改保持在最低限度,我认为您可以简单地改变您的行:

myString = myString & Cells(myRow, cell.Column) & ", "

是:

myString = myString & Format(CDate(Cells(myRow, cell.Column)), "dd mmm") & ", "