我是一个excel vba新手,我遇到了问题。能否请你指出正确的方向。
工作表中的日期结构为YYYYMMDD。 就本练习而言,开始日期为20060321,结束日期为20170512。 我有5个子程序(如果计算Exit子程序,则为6个子程序)。 SubA,SubB,SubC,SubD和SubE。 该程序从SubA开始,然后转到SubE。 当它到达SubE时,我希望它增加月份计数器。当它到达第12个月时,我希望它重置为01(回到1月),然后递增年度计数器。然后我想调用SubB(这是正确的 - SubB)。然后它需要循环,直到达到结束日期。
由于数据varYYYY的性质,varMM和varDD是字符串。所以我尝试将它们转换为Long,然后递增Long,然后将其转换回字符串。
~~~~~~~
我终于开始工作了。非常感谢Variatus分享他对如何从另一个子程序调用子程序的见解。这是让它运作的关键。不是循环结构不起作用。这是我不正当地使用调用导致不需要的循环的子程序。
我在这里粘贴了代码的简化和更新版本。
Option Explicit
Public varDD As String, varMM As String, varYYYY As String, varYYYYMM As String
Public varDayEnd As String, varMonthEnd As String, varYearEnd As String, varPrint As String
Public varA As String, varB As String, varC As String, varD As String, varE As String
Public varMMLong As Long, varYYYYLong As Long, i As Integer
Public varYearMonthEnd As String
Public Sub SubMain()
varDD = "21"
varMM = "03"
varYYYY = "2006"
varYearEnd = "2008"
varMonthEnd = "05"
varDayEnd = "12"
varA = "A"
varB = "B"
varC = "C"
varPrint = ""
varYearMonthEnd = varYearEnd & varMonthEnd
Debug.Print varYearMonthEnd
Do
varPrint = varYYYY & varMM & varDD
varMMLong = CLng(varMM)
varMMLong = varMMLong + 1
varMM = Format(varMMLong, "00")
varYYYYMM = varYYYY & varMM
SubA
SubB
SubC
If varMM = 13 Then
varDD = "01" ' reset varDD to 01
varMM = "01" ' reset varMM to Jan
varYYYYLong = CLng(varYYYY)
varYYYYLong = varYYYYLong + 1 ' increment by one year
varYYYY = Format(varYYYYLong, "0000")
End If
Loop Until varYYYYMM = varYearMonthEnd
End Sub
Public Sub SubA()
'Insert code block here
Debug.Print varA
End Sub
Public Sub SubB()
'Insert code block here
Debug.Print varB
End Sub
Public Sub SubC()
'Insert code block here
Debug.Print varC
End Sub
答案 0 :(得分:2)
这是一种更简单的方法,可以将字符串值转换为日期,然后将日期增加1天,最后将其转换回字符串。
Dim CurDt As Date, nextDt As Date
varDD = "21": varMM = "03": varYYYY = "2006"
CurDt = DateSerial(Val(varYYYY), Val(varMM), Val(varDD))
nextDt = DateAdd("d", 1, CurDt)
Debug.Print Format(nextDt, "YYYYMMDD")
答案 1 :(得分:0)
也许
Sub test()
Dim myY As Integer, myM As Integer, myD As Integer
Dim eY As Integer, eM As Integer, eD As Integer
Dim newDate As Date, sDate As Date, eDate As Date
Dim prn As String, i As Integer
myY = 2016: myM = 3: myD = 21
eY = 2017: eM = 5: eD = 12
vstr = Array("A", "B", "C", "D", "E")
sDate = DateSerial(myY, myM, myD)
eDate = DateSerial(eY, eM, 1)
Do
For i = 0 To UBound(vstr)
prn = prn & vstr(i)
Debug.Print prn
Next i
sDate = DateAdd("m", 1, sDate)
Loop While sDate < eDate
End Sub