跳到主要內容

 如何檢查文件夾是否存在以及是否創建文件夾?

您是否曾經嘗試從Excel工作表中檢查文件夾是否存在? 在本文中,我將討論檢查指定路徑中是否存在文件夾,如果不存在,該文件夾將在該路徑下自動創建。

使用VBA代碼檢查文件夾是否存在於特定文件路徑中

使用VBA代碼在特定文件路徑中不存在時創建文件夾


箭頭藍色右氣泡 使用VBA代碼檢查文件夾是否存在於特定文件路徑中

以下VBA代碼可以幫助您檢查特定文件路徑中是否存在文件夾,請執行以下操作:

1。 按住 ALT + F11 鍵打開 Microsoft Visual Basic for Applications 窗口。

2。 點擊 插入 > 模塊,然後將以下代碼粘貼到 模塊 窗口。

VBA代碼:檢查特定文件路徑中是否存在文件夾:

Sub Test_Folder_Exist_With_Dir()
'Updateby Extendoffice
    Dim sFolderPath As String
    sFolderPath = "C:\Users\DT168\Desktop\Test folder"
    If Right(sFolderPath, 1) <> "\" Then
        sFolderPath = sFolderPath & "\"
    End If
    If Dir(sFolderPath, vbDirectory) <> vbNullString Then
        MsgBox "Folder exist", vbInformation, "Kutools for Excel"
    Else
        MsgBox "Folder doesn't exist", vbInformation, "Kutools for Excel"
    End If
End Sub

注意: 在上面的代碼中,您應該更改文件夾路徑和名稱 C:\ Users \ DT168 \ Desktop \ Test文件夾 根據您的需要。

3。 然後按 F5 運行此代碼的關鍵,您將獲得以下結果:

doc文件夾存在1


箭頭藍色右氣泡 使用VBA代碼在特定文件路徑中不存在時創建文件夾

檢查文件夾是否存在於文件路徑中(如果不存在),以在此特定文件路徑下創建該文件夾,以下VBA代碼可以幫助您完成此工作。

1。 按住 ALT + F11 鍵打開 Microsoft Visual Basic for Applications 窗口。

2。 點擊 插入 > 模塊,然後將以下代碼粘貼到 模塊 窗口。

VBA代碼:如果文件路徑中不存在,請創建一個文件夾:

Sub MakeMyFolder()
'Updateby Extendoffice
    Dim fdObj As Object
    Application.ScreenUpdating = False
    Set fdObj = CreateObject("Scripting.FileSystemObject")
    If fdObj.FolderExists("C:\Users\DT168\Desktop\Test folder") Then
        MsgBox "Found it.", vbInformation, "Kutools for Excel"
    Else
        fdObj.CreateFolder ("C:\Users\DT168\Desktop\Test folder")
        MsgBox "It has been created.", vbInformation, "Kutools for Excel"
    End If
    Application.ScreenUpdating = True
End Sub

備註:在上面的代碼中,您應該更改文件夾路徑和名稱 C:\ Users \ DT168 \ Desktop \ Test文件夾 根據您的需要。

3。 粘貼代碼後,按 F5 運行它的關鍵:

(1.)如果該文件夾存在,則會彈出一個提示框,如下圖所示:

doc文件夾存在2

(2.)如果該文件夾不存在,則會立即在特定路徑下創建該文件夾,並且會彈出一個提示框,提醒您該文件夾已創建,請參見屏幕截圖:

doc文件夾存在3

最佳辦公生產力工具

🤖 Kutools 人工智慧助手:基於以下內容徹底改變數據分析: 智慧執行   |  生成代碼  |  建立自訂公式  |  分析數據並產生圖表  |  呼叫 Kutools 函數...
熱門特色: 尋找、突出顯示或識別重複項   |  刪除空白行   |  合併列或儲存格而不遺失數據   |   沒有公式的回合 ...
超級查詢: 多條件VLookup    多值VLookup  |   跨多個工作表的 VLookup   |   模糊查詢 ....
高級下拉列表: 快速建立下拉列表   |  依賴下拉列表   |  多選下拉列表 ....
欄目經理: 新增特定數量的列  |  移動列  |  切換隱藏列的可見性狀態  |  比較範圍和列 ...
特色功能: 網格焦點   |  設計圖   |   大方程式酒吧    工作簿和工作表管理器   |  資源庫 (自動文字)   |  日期選擇器   |  合併工作表   |  加密/解密單元格    按清單發送電子郵件   |  超級濾鏡   |   特殊過濾器 (過濾粗體/斜體/刪除線...)...
前 15 個工具集12 文本 工具 (添加文本, 刪除字符,...)   |   50+ 圖表 類型 (甘特圖,...)   |   40+ 實用 公式 (根據生日計算年齡,...)   |   19 插入 工具 (插入二維碼, 從路徑插入圖片,...)   |   12 轉化 工具 (數字到單詞, 貨幣兌換,...)   |   7 合併與拆分 工具 (高級合併行, 分裂細胞,...)   |   ... 和更多

使用 Kutools for Excel 增強您的 Excel 技能,體驗前所未有的效率。 Kutools for Excel 提供了 300 多種進階功能來提高生產力並節省時間。  點擊此處獲取您最需要的功能...

產品描述


Office選項卡為Office帶來了選項卡式界面,使您的工作更加輕鬆

  • 在Word,Excel,PowerPoint中啟用選項卡式編輯和閱讀,發布者,Access,Visio和Project。
  • 在同一窗口的新選項卡中而不是在新窗口中打開並創建多個文檔。
  • 將您的工作效率提高 50%,每天為您減少數百次鼠標點擊!
Comments (12)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Buonasera,

Non conosco il Vs. sito e mi sono imbattuto per caso su questa pagina.
Ho letto quanto scritto sopra e se è possibile avrei bisogno del Vs. aiuto.
Mi occorrerebbe una macro che in un percorso variabile ad un Host facente parte della stessa lan verifiche se è aperto un file exel dal nome variabile, e nel caso sia aperto chiuda il file e cancella tutto il contenuto della cartella compreso il file stesso.
Provo a spiegarmi meglio:
nel percorso :\\host01\Users\utente\Desktop\liste\Nome_Cognome_Gennaio\Operatore_16_Gennaio.xlsm
è presente un file excel dal nome : Operatore_16_Gennaio.xlsm

Il percorso non sempre è lo stesso così come il nome del file excel. Infatti il percorso cambia solo nel Nome_Cognome,es: :\\host01\Users\utente\Desktop\liste\Tizio_Caio_Gennaio\Operatore_16_Gennaio.xlsm) mentre nel file cambia solo il numero dell'operatore (Es: :\\host01\Users\utente\Desktop\liste\Sempronio_zeta_Gennaio\Operatore_15_Gennaio.xlsm.)

E' possibile avere una macro che fa quanto descritto sopra?

Ringrazio anticipatamente
This comment was minimized by the moderator on the site
How to create folder in desktop with vba whenever the excel book is opened, if exist, ignore.
Message if create new folder, silent if the folder exist.

Private Sub Workbook_Open()

Dim cOb As Variant
Dim FolderName As String, FolderExists As String
FolderName = "C:\Users\" & Environ("username") & "\Desktop\MyFolder\" '--->Change folder name to suit.
FolderExists = Dir(FolderName, vbDirectory)

Application.ScreenUpdating = False

If FolderExists = vbNullString Then
MsgBox "The desktop folder doesn't exist. Creating a new folder now.", vbExclamation, "INFORMATION"
cOb = CreateObject("wscript.shell").specialfolders("Desktop") & "\" & "MyFolder" '--->Change folder name to suit.
MkDir cOb
Else: Exit Sub
End If

Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
How to create folder in desktop with vba whenever the excel book is opened, if exist, ignore.
Message if create new folder, silent if the folder exist.


Private Sub Workbook_Open()

Dim cOb As Variant
Dim FolderName As String, FolderExists As String
FolderName = "C:\Users\AAAAA\Desktop\A New Folder" '---->Change folder name to suit. Change the AAAAA to your requirement.
FolderExists = Dir(FolderName, vbDirectory)

Application.ScreenUpdating = False

If FolderExists = vbNullString Then
MsgBox "The desktop folder doesn't exist. Creating a new folder now.", vbExclamation, "INFORMATION"
cOb = CreateObject("wscript.shell").specialfolders("Desktop") & "\" & "A New Folder" '--->Change folder name to suit.
MkDir cOb
Else: Exit Sub
End If

Application.ScreenUpdating = True

End Sub

This comment was minimized by the moderator on the site
excelente, me sirvió mucho el Objeto. Uso para carpetas como archivos. Muchas gracias
This comment was minimized by the moderator on the site
Hi, This works great, would there be any chance that the folder name used when checking if a folder already exists is derived from a cell within the spreadsheet, say A2??

I use a template spreadsheet which is updated automatically from another source, so cell A2 constantly changes which requires new folders being created in the same name.

Also, could there be such a command which does the above but also saves the active spreadsheet in the found / created folder?

Any hope? TIA
This comment was minimized by the moderator on the site
I'm running this macro, but in the step to create the folder, the process goes down.

can you help me????


'Comprobar si la carpeta existe

Dim ruta As String
Dim libro As String

M = ActiveWorkbook.Name

ruta = Application.Workbooks(M).Sheets("Diccionario").Range("B5").Value

If Right(ruta, 1) <> "\" Then
ruta = ruta & "\"
End If
If Dir(ruta, vbDirectory) <> vbNullString Then
MsgBox "Folder exist, please continue"
Else
MsgBox "Folder doesn't exist"
End If

'Crea la carpeta que necesitas

Dim fdObj As Object
Dim folder As String

folder = Application.Workbooks(M).Sheets("Dicionario").Range("B5").Value (here is where the process falls)

Application.ScreenUpdating = False
Set fdObj = CreateObject("Scripting.FileSystemObject")
If fdObj.FolderExists(folder) Then
MsgBox "Found it, pleace continue."
Else
fdObj.CreateFolder (folder)
MsgBox "It has been created."
End If
Application.ScreenUpdating = True
This comment was minimized by the moderator on the site
Super Thanks!
This comment was minimized by the moderator on the site
Thanks Man, work amazing
This comment was minimized by the moderator on the site
This is really helpful! thanks!
This comment was minimized by the moderator on the site
Great article. Just what I was looking for :)
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations