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

我有几个文件夹包含超过1000个子文件夹。 我必须将其中的一些(大约一半)移到其他位置,具体取决于每个子文件夹中的进度。 进度在电子数据表中标注,并提供path。 我有以下代码:

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

所以,这段代码会打开一个窗口资源pipe理器,并select一个文件(这个文件就是path+ ActiveCell值后面的文件。是否有一种方法可以一次select多个文件?比方说我想select200个单元格,所以Window Explorer将select200个文件打开?

感谢您的帮助!

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

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

按着这些次序。

  1. 打开一个模块并添加对Microsoft Shell Controls and AutomationMicrosoft Internet Controls的引用,如下所示

    在这里输入图像描述

  2. 接下来出于testing目的,我们将采用文件夹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 

输出:

在这里输入图像说明

Siddharth Rout的答案是非常有用的。 不过,它只能在窗口标题为"Windows Explorer" Windows平台上使用。

为了在Windows 8 / 8.1 / 10(而不仅仅是Windows 7的英文版)上运行,我们可以使用GetExplorer这个函数定义:

 '~~> Function to find the relevant 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 UCase(wb1.FullName) = "C:\WINDOWS\EXPLORER.EXE" Then If LCase(wb1.Document.Folder.Self.Path) = LCase(sFolder) Then Set GetExplorer = wb1 End If End If Next End Function