我有一个项目,我需要在一个区域中打开与一个区域相关联的所有区域文件,并在每个区域中循环。需要在等于或早于输入月份值的时间段(月)中打开该地区的所有文件。需要一次打开一个文件,并将该文件中某些变型工作表中的值复制并粘贴到另一个主文件中。文件的结构为Path \ Year \ District \ Period \ Territory.xlsx。
我在使用以下代码时遇到错误,该代码试图捕获报告的月份并将其与Period变量进行比较。我得到了下一步,没有For错误。
Sub DSMReports()
Sheets("START").Activate
Dim MM As Variant
Dim YYYY As Variant
MM = InputBox("Enter Month for reporting in MM format: 01-12")
YYYY = InputBox("Enter Year for reporting in YYYY format")
Range("C6").Value = MM
Range("C8").Value = YYYY
Dim DistrictDSM As Range
Dim DistrictsDSMList As Range
Set DistrictsDSMList = Start.Range("E11:E23")
Dim Path As String
Dim DistPeriodFile As String
Dim Total As Integer
Dim Period As Integer
For Each DistrictDSM In DistrictsDSMList.Cells
Total = 0
For Period = 1 To MM
Period = Total + 1
If Period < 10 Then Path = "\\corsrv027\Accounting\Monthend " & YYYY & "\DSM Files\" & DistrictDSM & "\P0" & Period
If Period >= 10 Then Path = "\\corsrv027\Accounting\Monthend " & YYYY & "\DSM Files\" & DistrictDSM & "\P" & Period
DistPeriodFile = Dir(Path & "\*.xlsx")
Do While DistPeriodFile <> ""
Workbooks.Open Filename:=Path & "\" & DistPeriodFile
'Do copying, pasting, and going through each worksheet one at a time here
DistPeriodFile = Dir
Next Period
Next DistrictDSM
Loop
End Sub
答案 0 :(得分:0)
通过将Next Without For
和Loop
之前的Do While
循环的Next Period
移动到{em> 来解决Next DistrictDSM
错误。缩进可视化并有助于正确构造循环,并会突出显示“交织”的循环结构。
For Each DistrictDSM In DistrictsDSMList.Cells
' code
For Period = 1 To MM
' more code
Do While DistPeriodFile <> ""
' more code
Loop
Next Period
Next DistrictDSM