繁体   English   中英

VBA:如果文件夹中的filename.dat包含X,请打开,运行宏,另存为filename.xlsm,然后关闭

[英]VBA: If filename.dat in folder contains X, open, run macro, save as filename.xlsm, close

我正在尝试创建一个宏,该宏将在文件夹中搜索名称中包含“ OPS”(不区分大小写)的.dat文件,如果找到了我想打开它并运行另一个宏的文件,请保存该文件作为原始的filename.xlsm,然后关闭。

到目前为止,我可以搜索名称,但这仅是我所了解的程度。

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文件,该宏就会运行。 任何帮助表示赞赏,谢谢。

在顶部添加

Dim wb as workbook

然后将您的消息框行替换为

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

我使用制表符分隔的文件进行了测试,效果很好。 如果使用其他格式,您的问题可能会有所不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM