在编码date中使用variables

我正在尝试拉取用户表单中选定月份和年份的所有数据条目。 我可以让代码运行良好,当我硬编码的一年,但我希望年从文本框中脱落。 我使用Cint()Textbox值转换为整数,并在if语句中将其变暗为“Year”。 如果我写Cdate("3/1/2016") ,我可以得到它的工作,但我想看看是否有办法像Cdate("3/1/Year") 。 我尝试了这种方式,并得到一个types错误的Cdate我相当新的VBA所以原谅我的愚蠢。

忽略“月”variables我刚刚使用,停下来的代码,并通过检查是否会进入我的if语句。

提前致谢。

我的代码

 Private Sub OKBtn_Click() Dim Sales As Range Dim Year As Integer Dim Month As Integer Dim i As Integer Year = CInt(YearText.Value) Set Sales = Worksheets("Sales").Range("A4") i = 0 If Sales.Offset(i, 1).Value >= CDate("3/1/2016") And Sales.Offset(i, 1).Value <= CDate(" 3/31/2016 ") Then Month = 1 End If 

为了CDate的工作,你需要将括号内的蜇伤分为2部分

常数,在你的情况“3/1 /”。

和variablesCInt(YearText.Value)

 Option Explicit Private Sub OKBtn_Click() Dim DDate As Date DDate = CDate("3/1/" & CInt(YearText.Value)) ' for debug only MsgBox "Date entered is :" & DDate End Sub