我正在创建一个代码,用于打开和导入基于客户端名称选择的文件中的数据。每次打开客户端时,都会为其保存一个文件,其中包含其名称和出生日期(不带斜线)。
示例文件看起来像C:\Data\Clients\John Doe 01011900.xlsx
。单击按钮上的InputBox会提供客户端的名称,但是如果文件夹中有2个或更多John Does,我会遇到的问题。
Check = Application.InputBox(prompt:="What is your client's first and last name?", Type:=2)
FilePath = "C:\Data\Clients\" & Check & "*.xlsx"
If Dir(FilePath, vbDirectory) = "" Then
Exit Sub
End If
DOB = MsgBox("Is this your client's date of birth? " & " " & Chr(149) & " " & Mid(Dir(FilePath), Len(Dir(FilePath)) - 12, 2) & "/" & Mid(Dir(FilePath), Len(Dir(FilePath) - 10, 2) & "/" & Mid(Dir(FilePath), Len(Dir(FilePath) - 8, 4) & " " & Chr(149), vbYesNoCancel)
If DOB = vbYes Then
Workbooks.Open (FilePath)
'Transfer Data
ActiveWorkbook.Close False
ElseIf DOB = vbNo Then
'Try again.
ElseIf DOB = vbCancel Then
'Do nothing.
End If
我的困惑发生在DOB = vbNo,当有人说出生日期不匹配时(意味着需要选择具有相同名称的下一个客户)。到目前为止,其他一切都很有效,所以我只需要帮助重新选择下一个同名文件。
答案 0 :(得分:2)
您可以通过在循环结束时添加strDir = Dir
来循环遍历所有匹配,这将在匹配满足后退出并且不被接受(因为StrDir
的长度将为0)
更新
我意识到代码看起来有点奇怪,但这是Dir
的工作方式,即每次调用它时,它会查找与初始Dir
相同的匹配,直到它到达结束时为止。名单。见Loop through files in a folder using VBA?
即
Do While Len(strDir) > 0
DOB = MsgBox("Is this your client's date of birth?", vbYesNoCancel)
If DOB = vbCancel Then Exit Do
If DOB = vbYes Then
Workbooks.Open (filepath)
ActiveWorkbook.Close False
Exit Do
End If
strDir = Dir
Loop
答案 1 :(得分:0)
这就是我要做的: 首先,使用字符串比较来查找以John Doe开头的目录中的所有文件,并将它们存储在动态数组中。
使用For...Each
语句浏览文件,然后使用
Dir(FilePath) LIKE "John Doe*"
找到你的候选人。
然后使用Do...While
循环遍历数组中的文件,直到找到匹配项。
我可以为你编写完整的代码但是你会错过所有的乐趣......