如何使用VBA从Excel中的选定单元格中选择Windows资源管理器中的多个文件?

Alo*_*Alo 3 excel vba excel-vba

我有几个文件夹,每个文件夹包含1000多个子文件夹.我必须将其中一些(大约一半)移动到其他位置,具体取决于每个子文件夹中的进度.电子表格中记录了进度,电子表格也提供了其路径.我有以下代码:

    Sub open_explorer()
    Shell "C:\Windows\explorer.exe /select, K:\user\folder\A\" & ActiveCell.Value, vbMaximizedFocus
    End Sub
Run Code Online (Sandbox Code Playgroud)

因此,此代码将打开一个窗口浏览器,其中选择了一个文件(这样的文件是跟随路径+ ActiveCell值的文件.有没有办法一次选择多个文件?让我说我想选择200个单元格,所以Window Explorer将打开所选的200个文件?

感谢您的帮助!

Sid*_*out 5

不幸的是,/select选项只会让您选择单个文件.没有其他选项可以让您选择多个文件.您可以通过查看此MS KB文章来确认

话虽如此,是否有可能在VBA中实现这一点,因为API SHOpenFolderAndSelectItems不可用?答案是

跟着这些步骤.

  1. 打开一个模块并添加一个参考Microsoft Shell Controls and AutomationMicrosoft Internet Controls,如下所示

    在此输入图像描述

  2. 接下来为了测试目的,我们将获取C:\Users\Siddharth Rout\Desktop\Test1具有5个csv文件的文件夹,编号从1到5,如下所示.

    在此输入图像描述

  3. 现在将以下代码粘贴到模块中并运行该过程 Sub Sample()

代码:

Option Explicit

Sub Sample()
    SelectMultipleFiles "C:\Users\Siddharth Rout\Desktop\Test1"
End Sub

Sub SelectMultipleFiles(sFolder As String)
    Dim wb As WebBrowser
    Dim objExp As Shell32.Shell

    Set objExp = New Shell32.Shell

    objExp.Open sFolder

    '~~> Find our explorer window
    Do While wb Is Nothing: Set wb = GetExplorer(sFolder): Loop

    '~~> We are going to select files 1,3 and 5.csv
    '~~> The 5& is used so that any previous selections are cleared off
    Call wb.document.SelectItem(sFolder & "\1.csv", 5&)
    Call wb.document.SelectItem(sFolder & "\3.csv", 1&)
    Call wb.document.SelectItem(sFolder & "\5.csv", 1&)
End Sub

'~~> Function to find the releavnt explorer window
Function GetExplorer(sFolder As String) As WebBrowser
    Dim objExp As New Shell32.Shell
    Dim wb1 As WebBrowser

    For Each wb1 In objExp.Windows
        If wb1.Name = "Windows Explorer" And _
        LCase(wb1.document.Folder.Self.Path) = LCase(sFolder) Then
            Set GetExplorer = wb1
        End If
    Next
End Function
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述