VBA代码实现获取文件夹文件所有者并统计当前用户PDF文件数
VBA获取文件所有者并统计当前用户PDF数量的修复方案
完整可运行代码
Option Explicit Sub CountCurrentUserPDFs() Dim folderPath As String Dim currentUser As String Dim fileCount As Integer Dim fs As Object, file As Object ' 获取当前登录用户名 currentUser = Environ("USERNAME") fileCount = 0 ' 让用户选择目标文件夹 With Application.FileDialog(msoFileDialogFolderPicker) If .Show = -1 Then folderPath = .SelectedItems(1) & "\" Else MsgBox "未选择文件夹,程序终止。", vbExclamation Exit Sub End If End With ' 遍历文件夹内所有文件 Set fs = CreateObject("Scripting.FileSystemObject") For Each file In fs.GetFolder(folderPath).Files ' 只处理PDF格式文件 If LCase(fs.GetExtensionName(file.Path)) = "pdf" Then ' 调用函数获取文件所有者 Dim owner As String owner = GetFileOwner(file.Path) ' 判断是否为当前用户(兼容带域名的所有者格式) If InStr(1, owner, currentUser, vbTextCompare) > 0 Then fileCount = fileCount + 1 End If End If Next file MsgBox "当前用户拥有的PDF文件数量:" & fileCount, vbInformation End Sub ' 修复后的文件所有者获取函数 Function GetFileOwner(filePath As String) As String Dim objWMIService As Object Dim colItems As Object Dim objItem As Object Dim strOwner As String ' 转换路径格式为WMI要求的双反斜杠 filePath = Replace(filePath, "\", "\\") ' 连接WMI服务查询文件安全设置 Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalFileSecuritySetting WHERE Path='" & filePath & "'") ' 提取所有者名称 For Each objItem In colItems strOwner = objItem.GetSecurityDescriptor().Owner.Name Exit For Next objItem GetFileOwner = strOwner End Function
关键修复点说明
修复
GetFileOwner函数:- 改用WMI接口获取文件所有者,这是Windows系统原生的可靠方式,无需手动指定所有者变量,自动适配每个文件的实际所有者。
- 处理路径格式:WMI查询要求路径中的单个反斜杠替换为双反斜杠,否则会查询失败。
- 通过
GetSecurityDescriptor().Owner.Name直接提取所有者名称,结果可能是域名\用户名或本地用户名格式。
优化用户匹配逻辑:
使用InStr进行不区分大小写的模糊匹配,避免因所有者名称带域名前缀导致匹配失败的问题。增加异常处理:
当用户取消文件夹选择时,弹出提示并终止程序,避免后续代码报错。
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

