Combining two vba functions

时间:2018-05-18 17:13:33

标签: vba excel-vba excel

I have the following VBA functions in Excel (datecleanup and date1) that I would like to combine together into date1. Or preferably take the logic in dateclean and put into date1. This I'm sure is very simple, however I am new to VBA and not sure how I can accomplish this.

datecleanup function:

Function datecleanup(inputdate As Variant) As Variant

If Len(inputdate) = 0 Then
  inputdate = "01/01/1901"
Else
  If Len(inputdate) = 4 Then
    inputdate = "01/01/" & inputdate
  Else
    If InStr(1, inputdate, ".") Then
        inputdate = Replace(inputdate, ".", "/")
    End If
    dateclean = Split(strInput, Chr(32))(0)
  End If
End If
End Function

date1 function:

datecleanup = inputdate

Function date1(strInput) As String
 date1 = Split(strInput, Chr(32))(0)

End Function

I would like the date1 logic to occur as the final part of the dateclean function. How can I accomplish this? Thanks very much!

EDIT:

This is the correct datecleanup function:

Function datecleanup(inputdate As Variant) As Variant

If Len(inputdate) = 0 Then
    inputdate = "01/01/1901"
Else
  If Len(inputdate) = 4 Then
    inputdate = "01/01/" & inputdate
  Else
    If InStr(1, inputdate, ".") Then
        inputdate = Replace(inputdate, ".", "/")
    End If

  End If
End If

datecleanup = inputdate

End Function

1 个答案:

答案 0 :(得分:2)

这里有一些清理过的逻辑,它们都组合成一个函数:

Function datecleanup(inputdate As Variant) As String

    If Len(inputdate) = 0 Then
        inputdate = "01/01/1901"
    ElseIf Len(inputdate) = 4 Then
        inputdate = "01/01/" & inputdate
    ElseIf InStr(1, inputdate, ".") Then
        inputdate = Replace(inputdate, ".", "/")
    End If  

    datecleanup = Split(inputDate, Chr(32))(0)
End Function

或者,您可以将它们分开保存,只需在datecleanup函数中调用date1函数:

Private Function datecleanup(inputdate As Variant) As String
    If Len(inputdate) = 0 Then
        inputdate = "01/01/1901"
    ElseIf Len(inputdate) = 4 Then
        inputdate = "01/01/" & inputdate
    ElseIf InStr(1, inputdate, ".") Then
        inputdate = Replace(inputdate, ".", "/")
    End If  

    datecleanup = inputdate     
End Function

Function date1(strInput) As String
    date1 = Split(datecleanup(strInput), Chr(32))(0)
End Function

这很好,因为它保持逻辑分离(如果这是可取的......)