我打算创建一个宏来查找与当前年份相对应的文件并循环显示其工作表。工作表的名称对应于月份名称(瑞典语)。我的问题是,由于我可能删除了我导入的文件中的数据等,我不想导入输入超过2个月前的数据,并从相应的月份循环到今天的月份(好吧,实际上是UBound(MyHeadings)作为我想提取的一些数据在一年中是不变的。
Dim MonthNo As Integer 'Makes MonthNo = Month(Date) return an integer, instead of actual month name
MonthNo = Month(Date)
myHeadings = Split("Januari,Februari,Mars,April,Maj,Juni,Juli,Augusti,September,Oktober,November,December", ",")
p3file = "C:\pathtofile\" 'Because Dir does not return pathfile.
YearNo = Year(Date)
path3 = IIF(MonthNo-2, Dir("C:\pathtofile\" & "-" & YearNo-1 & ".xlsx"),Dir("C:\pathtofile\" & "-" & YearNo & ".xlsx"))
Do While Len(path3) > 0
Set openWb = Workbooks.Open(p3file & path3)
For i = MonthNo To UBound(myHeadings)
Set openWs = openWb.Sheets(CStr(YearNo))
'Do things
End If
Next i
YearNo = YearNo + 1
path3 = Dir("C:\pathtofile\" & YearNo & ".xlsx")
Loop
以上是我尝试过的。如果MonthNo -2小于0,则会出现问题,因为那时我必须导入上一年的文件(我通过IIf语句执行)。然而,循环变得错误。例如,如果当前月份是2015年1月,我想打开2014年的文件,循环到11月和12月,然后打开2015年文件并循环到1月。是否有任何巧妙的方法来实现这一目标?
答案 0 :(得分:1)
您的代码可能如下所示:
Dim MonthNo As Integer, YearNo As Integer
Dim CurrentYear As Integer
Dim StartDate As Date
Dim i As Integer
Const MonthOffset As Integer = -2
CurrentYear = Year(Date)
StartDate = DateAdd("m", MonthOffset, Date)
MonthNo = Month(StartDate)
YearNo = Year(StartDate)
Do While YearNo <= CurrentYear
'Open file here
For i = MonthNo To 12
'Process sheets here
Next i
MonthNo = 1
YearNo = YearNo + 1
Loop
对于常量中定义的任何月偏移量,此代码应该可以正常工作。