![從檔案對話框 {Folder] 添加檔案時檢查串列框是否已經有檔案](https://img.uj5u.com/2022/03/29/a650e56bd42a42b89ee7d7d240065b7d.jpg)
Good day guys, I created a form in MS Access and I am trying to write some codes that prevents duplication of files when it is added to a listbox. As it is now, if I select the folder of interest and click on Display button, it re-adds the same files already in the listbox. Please advise. Below is my code so far:
Public Sub btn_folderimp_Click()
' Displays Excel SpreadSheets In Selected Folder
Dim myFSO As New FileSystemObject
Dim MyFile As File
Dim mFolder As Folder
' Dim lbx As ListBox
'Checks If No Folder Was Selected
If Nz(Me.txt_folderpath, "") = "" Then
Beep
MsgBox "No Folder Selected!"
Exit Sub
End If
'Checks If Folder Exists, If Yes, it displays a list of spreadsheets in the Folder
If myFSO.FolderExists(Nz(Me.txt_folderpath, "")) Then
Set mFolder = myFSO.GetFolder(Me.txt_folderpath)
For Each MyFile In mFolder.Files
If (myFSO.GetExtensionName(MyFile.Name) = "xlsx") Then 'Or (myFSO.GetExtensionName(MyFile.Name) = "xls")
Me.lbx_show.AddItem MyFile.Path
' Debug.Print MyFile
End If
Next MyFile
' Checks if there are excel spreadsheets in the folder
If Dir(Me.txt_folderpath & "*.xlsx") = "" Then
Beep
MsgBox "No Excel Spreadsheet Found!"
End If
Else
Beep
MsgBox "Folder Does Not Exist"
End If
End Sub
uj5u.com熱心網友回復:
我猜你想為你在文本框中選擇的每個目錄添加檔案到串列框中,如果你第二次在你的帖子中運行代碼,它不應該再次添加相同的檔案。您可以通過使用字典并將檔案名添加到字典中來做到這一點
Option Compare Database
Option Explicit
' Dictionary for the filenames
Dim dict As New Scripting.Dictionary
Public Sub btn_folderimp_Click()
' Displays Excel SpreadSheets In Selected Folder
Dim myFSO As New FileSystemObject
Dim MyFile As File
Dim mFolder As Folder
' Dim lbx As ListBox
'Checks If No Folder Was Selected
If Nz(Me.txt_folderpath, "") = "" Then
Beep
MsgBox "No Folder Selected!"
Exit Sub
End If
' clear the listbox
lbx_show.RowSource = ""
'Checks If Folder Exists, If Yes, it displays a list of spreadsheets in the Folder
If myFSO.FolderExists(Nz(Me.txt_folderpath, "")) Then
Set mFolder = myFSO.GetFolder(Me.txt_folderpath)
For Each MyFile In mFolder.Files
If (myFSO.GetExtensionName(MyFile.Name) = "xlsx") Then 'Or (myFSO.GetExtensionName(MyFile.Name) = "xls")
' will add a new entry if it not exists
dict(MyFile.Path) = MyFile.Path
'Me.lbx_show.AddItem MyFile.Path
End If
Next MyFile
' add the filenames to the listbox
Dim key As Variant
For Each key In dict.Keys
Me.lbx_show.AddItem key
Next
' Checks if there are excel spreadsheets in the folder
If Dir(Me.txt_folderpath & "*.xlsx") = "" Then
Beep
MsgBox "No Excel Spreadsheet Found!"
End If
Else
Beep
MsgBox "Folder Does Not Exist"
End If
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/451395.html
上一篇:cmd
下一篇:呼叫具有2個變數的函式
