VB Do While only works for one iteration

2020-04-11 11:26发布

I've never done anything before with VB and am trying to work out a little problem with this script. Basically the script should look for all jpgs in a folder, if the file name exists already remove it from the target folder, add the value to a table and then rename the source file so it exists in the target folder.

This script works to an extent, for example it will rename any file if the file doesn't exist already but for any files that do already exist it processes only one then then ends. I can run it multiple times to clear the rest but would rather it cleared them all in one go. I have done quite a bit of reading but can't see what is going wrong. Can anyone shed any light on this?

Public Function GetLPUFileAddress()

Dim strSourceFolder As String
Dim strFile As String
Dim strTargetFolder As String

Dim dbs As DAO.Database
Dim rstMgr As DAO.Recordset

strSourceFolder = "C:\Users\Images\LPU-HOLDING\"
strFile = Dir(strSourceFolder & "*.JPG")
strTargetFolder = "C:\Users\Images\LPU\"

Do While strFile <> ""
    If Dir(strTargetFolder & strFile) <> "" Then Kill strTargetFolder & strFile
    CurrentDb.Execute "INSERT INTO TBL_LPU ( File_Name, Import_Date ) VALUES ('" & strFile & "',Date())"
    Name strSourceFolder & strFile As strTargetFolder & strFile
    strFile = Dir
Loop

End Function

标签: vbscript
1条回答
欢心
2楼-- · 2020-04-11 12:11

By calling the Dir() function with an appropriate filter, such as "C:\Users\Images\LPU\*.JPG", you start enumeration and get the first file name.
After that, repeatedly calling the Dir() function without any parameters, you will get all *.JPG file names, one for each call.
If you at any point call Dir() with a parameter, this will reset the current enumeration and start a new one.

You therefore can't use Dir() to check existance of a file in a folder while you're enumerating with Dir(). This resets the enumeration.

You have to either use some other way of checking existance of the file, or just try to kill it without checking, ignoring the error.

查看更多
登录 后发表回答