VBA:如果文件夹中的filename.dat包含X,则打开,运行macros,保存为filename.xlsm,closures

我试图创build一个macros,将search一个.dat文件的名称中包含“OPS”(不区分大小写)的文件夹,如果它find一个文件,我想打开它并运行另一个macros,保存该文件作为原始文件名.xlsm,并closures。

到目前为止,我能够search名字,但这是关于我的知识的程度。

Sub Test2() Dim sh As Worksheet, lr As Long, fPath As String, fName As String, rFile() As Variant fPath = "C:\Users\ntunstall\Desktop\test\" ctr = 1 fName = dir(fPath & "*.dat") Do Until fName = "" If InStr(fName, "OPS") > 0 Then ReDim Preserve rFile(1 To ctr) rFile(ctr) = fName ctr = ctr + 1 End If fName = dir Loop For i = LBound(rFile) To UBound(rFile) 'The variable rFile(i) represents the workbooks you want to work with. MsgBox rFile(i) Next End Sub 

理想情况下,只要打开包含OPS的.dat文件,该macros就会运行。 任何帮助表示赞赏,谢谢。

到顶部添加

 Dim wb as workbook 

然后用您的消息框行replace

 Set wb = Workbooks.Open(fPath & rFile(i)) wb.SaveAs fPath & Split(rFile(i), ".")(0), xlOpenXMLWorkbookMacroEnabled wb.Close 

我testing了一个选项卡删除文件,它运作良好。 如果您有不同的格式,您的问题可能会有所不同。