Fork me on GitHub

VBA - 获取当前路径下的excel文件,并隐藏打开

Sub ReadFilesInFolder()
    Dim filePath As String
    Dim otherExcelFileName As String
    Dim wb As Workbook
    

    'Excel.Application.DisplayAlerts = False
    Excel.Application.ScreenUpdating = False
    ' 设置目录路径
    filePath = ThisWorkbook.Path & "\"
    
    ' 获取第一个文件的文件名
    otherExcelFileName = Dir(filePath & "*.xlsx")
    
    Dim newApp As Excel.Application
    Dim newWb As Workbook
    
    Set newApp = New Excel.Application  ' 创建新实例
    newApp.Visible = False              ' 隐藏新创建的EXCEL进程

    ' 遍历目录下的所有文件
    Do While otherExcelFileName <> ""
        ' 打印文件名
        Debug.Print otherExcelFileName
        
        ' 打开每个找到的Excel文件
        Set newWb = newApp.Workbooks.Open(filePath & otherExcelFileName)
        newWb.Sheets(1).Range("a1") = 520
        ' 关闭当前工作簿,保存更改
        newWb.Close SaveChanges:=True        ' 操作后关闭
        
        
        ' 获取下一个文件的文件名
        otherExcelFileName = Dir

    Loop
    
    newApp.Quit                        ' 退出实例
    Set newApp = Nothing               ' 释放资源
    Excel.Application.ScreenUpdating = True
    'Excel.Application.DisplayAlerts = True
End Sub

  

posted @ 2011-09-14 23:42  逍遥メ风  阅读(173)  评论(0)    收藏  举报