[英]Check if the folder is empty
我的代码应遍历Folders / Subs,并确定其中是否有任何文件。
我有两个问题:
如果某些文件夹中没有文件夹/订阅,我没有收到任何反馈。 一种特殊情况:如果它检测到文件(不是文件夹),则假定程序中显示“ Empty Folder”(空文件夹),其中包含一些文件(例如Excel)?
在“打开窗口”对话框中选择一个文件夹,如果单击“取消”,则会显示一个弹出窗口,说明:“文件夹不为空。.blabla...”
Sub Button1_click()
Dim FileSystem As Object
Dim HostFolder As String
Dim Answer As String
Dim fs, strFolderPath, oFolder
' *** Folder with Files to perform an action ***
HostFolder = GetSourceFolder()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' *** This is your folder to define ***
Set fs = CreateObject("Scripting.FileSystemObject")
strFolderPath = Application.ActiveWorkbook.Path
Set oFolder = fs.getfolder(strFolderPath)
If (oFolder.SubFolders.Count = 0) Then
' *** If folder is empty/full message ***
' * Folder is Empty *
MsgBox "Folder is empty!", vbOKOnly + vbInformation, "Information!"
Else
' * Folder isn't empty *
Answer = MsgBox("Folder not empty! Proceed with Macro?", vbYesNo + vbInformation + vbDefaultButton1, "Information!")
If Answer = vbNo Then Exit Sub
End If
Set fs = Nothing
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Dim targetFolder As String
targetFolder = GetTargetFolder()
DoFolder FileSystem.getfolder(HostFolder)
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Function GetSourceFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select Source Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetSourceFolder = sItem
Set fldr = Nothing
End Function
Function GetTargetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select Output Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetTargetFolder = sItem
Set fldr = Nothing
End Function
如果要单独进行选择文件夹的过程,则需要确定用户是否选择了任何内容。 您可以将函数的Boolean
返回类型用作操作的结果,并可以使用引用传递的源文件夹的字符串,如果用户选择了文件夹,则将其填充。 这是基本代码:
Sub Test()
Dim sourceFolder As String
'// Usage
If Not GetSourceFolder(sourceFolder) Then
MsgBox "No folder selected", vbExclamation
Exit Sub
End If
'// Go on with your code
End Sub
Function GetSourceFolder(ByRef sourceFolder As String) As Boolean
'// By default function will return False
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show Then
sourceFolder = .SelectedItems(1)
GetSourceFolder = True
End If
End With
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.