我目前正在搜索VBA中的用户自定义功能,同时搜索其他一些工作簿。我在将FileName
函数中的Dir()
表达式转换为路径目录时遇到问题,在我的文件夹名称之后使用正确的反斜杠,然后在File
周围使用通配符以允许Dir搜索所有出现的关键字。目前我认为\被省略了,我还不知道我的通配符是否正常工作
' Modify this folder path to point to the files you want to use.
Folder = InputBox("Enter folder directory of files")
' e.g C:\peter\management\Test Folder
File = InputBox("Enter filename keyword")
'e.g. PLACE
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(Folder & "\" & "*" & File & "*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
我假设我的语法不正确,我想要实现的目标。任何帮助将不胜感激!
编辑:
' Modify this folder path to point to the files you want to use.
Folder = InputBox("Enter folder directory of files")
' e.g C:\peter\management\Test Folder
File = InputBox("Enter filename keyword")
'e.g. PLACE
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(Folder & "\" & File & "*" & ".xls")
Debug.Print (FileName)
' Loop until Dir returns an empty string.
Do While FileName <> ""
我目前正在与之合作。 &#34; \&#34;在我的Dir行中似乎没有做任何事情,因为我仍然需要在文件之前手动添加最终\以使其显示在我的错误消息中。
答案 0 :(得分:0)
当我尝试你的代码时,它对我有用。毋庸置疑,这使得提供满意答案变得有点棘手!
以下是我尝试解决同样的问题。
而不是要求用户手动输入我使用Excel's built-in folder picker的文件夹地址。这避免了检查和处理拼写错误的需要。
Sub FindFiles()
Dim fldDialog As FileDialog ' Holds a reference to the folder picker.
Dim path As String ' Folder selected by user.
Dim fileFilter As String ' Provided by user, wildcard supported.
Dim found As String ' Used to display returned results.
' Config dialog.
Set fldDialog = Application.FileDialog(msoFileDialogFolderPicker)
fldDialog.Title = "Pick a folder" ' Caption for dialog.
fldDialog.AllowMultiSelect = False ' Limit to one folder.
fldDialog.InitialFileName = "C:\" ' Default starting folder.
' Display to user.
If fldDialog.Show Then
' Config filter.
path = fldDialog.SelectedItems(1)
fileFilter = InputBox("Select a filter (*.*)", "File filter", "*.*")
' Get results.
found = Dir(path & "\" & fileFilter)
Do Until found = vbNullString
MsgBox found, vbInformation, "File found"
found = Dir()
Loop
Else
MsgBox "User pressed cancel", vbInformation, "Folder picker"
End If
End Sub