VBA-“ Do While循环”返回Dir<无效的过程调用或参数> [英] VBA - Do While Loop returns Dir <Invalid procedure call or argument>

查看:447
本文介绍了VBA-“ Do While循环”返回Dir<无效的过程调用或参数>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历一个文件夹以获取完整的文件名地址(文件夹地址+文件名和扩展名)。



我正在使用以下命令,但在某些时候Dir值是<无效的过程调用或参数>

  recsFolder = Functions.GetFolder( C:\)
recfile = recsFolder& \和Dir(recsFolder& \ * .rec *)
Do While Len(recfile)> 0
recfile = recsFolder& \和Dir
循环

在读取完所有文件后,在循环之前抛出错误。 / p>

编辑:另一种方法,每次我按F8时Dir都在更改

 如果Right(recsFolder,1)<>  \,然后recsFolder = recsFolder&  \ 
numFiles = 0
recfile = Dir(recsFolder)
while recfile<>
numFiles = numFiles + 1
recfile = Dir()
Wend

我正在尝试这种最新方法,但遇到相同的错误。问题是,当我逐行(F8)运行代码时,每次在While中运行新代码行时,我都会看到Dir值更改。

解决方案

代替DIR,怎么办?

 'enable Tools-> References, Microsoft脚本运行时

Sub Test()
Dim fso作为新Scripting.FileSystemObject
Dim fldr作为文件夹

设置fldr = fso.GetFolder( C:\test)
HandleFolder fldr
End Sub


Sub HandleFolder(fldr As Folder)
Dim f As File
Dim subFldr As文件夹

'循环通过此文件夹中的文件
在fldr.Files
中进行f调试。打印f.Path
下一个

'通过子文件夹
在fldr.SubFolders中的每个subFldr
HandleFolder subFldr
下一个
End Sub


I am running a loop through a folder in order to get the complete filename address (folders address + file name and extension).

I am using the following, but at some point the Dir value is <Invalid procedure call or argument>

recsFolder = Functions.GetFolder("C:\")
recfile = recsFolder & "\" & Dir(recsFolder & "\*.rec*")
Do While Len(recfile) > 0
   recfile = recsFolder & "\" & Dir
Loop

The error is thrown before the loop as completed reading all the files.

EDIT: another approach and Dir is changing everytime I press F8

If Right(recsFolder, 1) <> "\" Then recsFolder = recsFolder & "\"
numFiles = 0
recfile = Dir(recsFolder)
While recfile <> ""
    numFiles = numFiles + 1
    recfile = Dir()
Wend

I am trying this latest approach and I get the same error. The problem is that when I run the code line by line (F8) I can see that the Dir value changes everytime a new line of code is run inside the While.

解决方案

Instead of DIR, how about this:

' enable Tools->References, Microsoft Scripting Runtime

Sub Test()
    Dim fso As New Scripting.FileSystemObject
    Dim fldr As Folder

    Set fldr = fso.GetFolder("C:\test")
    HandleFolder fldr
End Sub


Sub HandleFolder(fldr As Folder)
    Dim f As File
    Dim subFldr As Folder

    ' loop thru files in this folder
    For Each f In fldr.Files
        Debug.Print f.Path
    Next

    ' loop thru subfolders
    For Each subFldr In fldr.SubFolders
        HandleFolder subFldr
    Next
End Sub

这篇关于VBA-“ Do While循环”返回Dir&lt;无效的过程调用或参数&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆