2016-08-05 106 views
0

我有一個問題:VBA函數不能返回值主副

現在,我得到一個日期範圍主要子(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,但它仍然無法正常工作。我如何將日期值返回到主子?

非常感謝提前!

+3

你不會從你的函數返回任何東西。你錯過了這一行:'findstartdate = startdate' –

+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 
+0

非常感謝!其實我的任務是從谷歌分析中提取csv文件中的條目,因此輸入是字符串。 –