Do while循环不循环也不执行

时间:2016-04-14 12:36:38

标签: excel vba excel-vba do-while

寻求进一步永远不再做任何手册 我创建了一个it.xlsm,你必须将它放在一个文件夹中,该文件夹中包含一个必须处理的特定文件。

这个it.xslm有三个模块:

主文件 - 重命名C中的类别 - 在C中制作每个类别的工作表 - 将这些工作表保存为.xslx。这导致/ Departement文件夹中的8个新文件

Littlefiles
- 重写E中的类别 - 为每个类别制作标签
- 清理空列。

占位符
使用数据打开.xls 应用Masterfile
打开由主文件创建的所有文件 制作标签并清理空列。

占位符代码:

Sub OpenBigFile()
Dim wb As Workbook

Dim ws As Worksheet
Dim Lastrow As Long
'open main file, apply masterfile moduke
Set wb = Workbooks.Open(ThisWorkbook.path & "\Depositformulier (Reacties).xlsx")

Call masterfile.total

wb.Close SaveChanges:=True

End Sub

这很好用。

    Sub OpenAllFiles()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String


   myPath = ThisWorkbook.path & "\" & "Departement" & "\"
   myFile = Dir(myPath & "*.xlsx")


  Do While Len(Filename) > 0
  DoEvents
     Set wb = Workbooks.Open(myPath & myFile, True, True)

        Call LittleFiles.total

      wb.Close False

      myFile = Dir
  Loop


End Sub

在这里,我发现自己遇到了问题。我尝试使用很多例子多次重写它,但似乎总是陷入Set wb = Workbooks.Open(Filename:=myPath & myFile)

我做错了什么? 你需要我的Littlefiles代码吗?

另外,一般情况下,即使同时另一个工作簿处于活动状态(这是ActiveWorkbook),“ThisWorkbook”将始终引用this.xlm是否正确?

非常感谢

2 个答案:

答案 0 :(得分:0)

尝试与此相似的内容

 path = "path2folder" & "\"  'this is fairly important and probably why your code breaks?_
                               you cant add the backslash like you do above
 Filename = Dir(path & "*.xl??")

 Do While Len(Filename) > 0
     DoEvents
     Set wbk = Workbooks.Open(path & Filename, True, True)
         'add your code
     wbk.Close False
     Filename = Dir
 Loop

答案 1 :(得分:0)

这是我的尝试,我认为这样会更难以出错,因为您将拥有已存储文件的完整路径:

Sub OpenAllFiles()
'create an array
Dim myFiles As Variant
ReDim myFiles(500)

myPath = ThisWorkbook.Path

If Right(myPath, 1) <> "\" Then
myPath = myPath & "\"
End If


'search for at least 5 files in the folder specified above, add the entire path to the array
While myCount < 5
    If Dir(myPath & "*.xlsm") <> "" Then
    potentialFileToLoad = Dir(myPath & "*.xlsm")
    While potentialFileToLoad <> ""
        myFiles(myCount) = myPath & potentialFileToLoad
        myCount = myCount + 1
        potentialFileToLoad = Dir
    Wend

    End If
Wend

'change size of array to ammount of files found
ReDim Preserve myFiles(myCount - 1)

For Each ii In myFiles

'(Insert Open, Run code, close code here)
Workbooks.Open (ii), True, True

Call LittleFiles.Total

ActiveWorkbook.Close

Next ii

End Sub