如果文件基本名称的一部分是相同的,使用vb for excel几个文件select

我正面临一个典型的问题,我必须select包含相同的基本名称(部分)和不同的扩展名,如pdf,xls,idf等文件。我可以使用filedialog允许手动select,但我必须重复操作几次,这是非常繁琐的过程。 所以我期待着用vb excel来迭代。

目前,我向一些使用linux编程的同事求助,这是我不喜欢的。

我必须随后对它们进行一些操作,比如重命名,移动等。我可以成功执行这些任务。

这个macros演示了Dir函数的不同用法:

 Option Explicit Sub DemoDir() Dim FileName As String Dim PathName As String ' This gets the path of the active workbook. I find it convenient ' with this type of task, to place the workbook containing the macro ' in the folder holding the files I want to examine. Alternatively, ' you can set PathName to any folder you can reach. PathName = ActiveWorkbook.Path ' This locates each file in PathName with a name starting with "Token" ' and an extension of "txt". It output the name of each file located to ' the Immediate Window. This is an easy way to check you are finding ' the correct files. FileName = Dir$(PathName & "\Token*.txt") Do While FileName <> "" Debug.Print FileName FileName = Dir$ Loop Debug.Print "-------------------------------" ' This locates each file in PathName with a name starting with "T" ' and any extension. FileName = Dir$(PathName & "\T*.*") Do While FileName <> "" Debug.Print FileName FileName = Dir$ Loop Debug.Print "-------------------------------" ' This locates each file in PathName with a name starting with "Te" ' and whose fourth character is "t" and whose extension starts with "x". FileName = Dir$(PathName & "\Te?t*.x*") Do While FileName <> "" Debug.Print FileName FileName = Dir$ Loop End Sub 

上面的macros仅将文件名列出到立即窗口。 如果你想重命名或移动文件,你需要使用Name语句。 我发现名称Name混淆和无益,但它做你想要的。 其语法是:

oldpathname命名 newpathname

在VB编辑器的帮助中查找Name语句以获取更多信息。