VBA函数无法将值返回到主子

时间:2016-08-05 12:38:37

标签: vba excel-vba excel

我遇到了问题:

现在我得到了一个主子(20160706-20160805)的日期范围,我必须将值分开并将其作为日期。我所做的是:

Main sub date () 

Dim strDaterage as string 

Dim startdate as date 

'For the sake of simplicity, just use the hard code for the date 

strDaterange = "20160706-20160805"

startdate = findstartdate()

msgbox (startdate)

End sub 

并且用于分隔日期的函数提取值:

Function findstartdate()

    daterange = "20160706-20160805"
    startDateange = Left(daterange, 8)
    startYear = Left(startDateange, 4)
    startMonth = Mid(startDateange, 5, 2)
    startDay = Right(startDateange, 2)
    startdate = DateSerial(startYear, startMonth, startDay)

End Function

我尝试使用byval和byfer但它仍然不起作用。如何将日期值返回到主子?

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

不确定为什么使用String作为输入,但如果您愿意,可以使用下面的代码(有更有效的方法)。

你的潜艇:

Sub SubDate()

Dim strDaterage     As String
Dim startdate       As Date

strDaterage = "20160706-20160805"
startdate = findstartdate(strDaterage)

MsgBox (startdate)

End Sub

你的职能:

' need to add a String variable as an input, and return tha value as a Date
Function findstartdate(DateRange As String) As Date

startDateange = Left(DateRange, 8)
startYear = Left(startDateange, 4)
startMonth = Mid(startDateange, 5, 2)
startDay = Right(startDateange, 2)

startdate = DateSerial(startYear, startMonth, startDay)

' convert the string result to a Date
findstartdate = CDate(startdate)

End Function