vba打开遍历文件夹

‘遍历每个文件,并且修改文件,先将文件的名字存在数组中,然后通过数组遍历打开每个文件,修改,再关闭文件~

Sub OpenCloseArray()
    Dim MyFile As String
    Dim Arr(100) As String
    Dim count As Integer
    MyFile = Dir("D:\data\data2\" & "*.xlsx")
    count = count + 1
    Arr(count) = MyFile
     
    Do While MyFile <> ""
        MyFile = Dir
        If MyFile = "" Then
            Exit Do
        End If
        count = count + 1
        Arr(count) = MyFile         '将文件的名字存在数组中
    Loop
     
    For i = 1 To count
        Workbooks.Open Filename:="d:\data\data2\" & Arr(i)  '循环打开Excel文件
            Sheet1.Cells(2, 2) = "alex_bn_lee"             '修改打开文件的内容
        ActiveWorkbook.Close savechanges = True     '关闭打开的文件
    Next
‘要是想要修改每个工作簿的内容可以这样遍历一下,显示将文件夹中的工作簿的名字存到’一个字符串数组中,然后在用For...Next语句遍历

VBA读取其他Excel文件内容

Sub vbaTest()
    '数据读取
'----------------------------------------------
    Dim dataExcel, Workbook, sheet
    Dim totalRow As Integer
    Set dataExcel = CreateObject("Excel.Application")
    Set Workbook = dataExcel.Workbooks.Open(ThisWorkbook.Path & "\finall.xls")
    Set sheet = Workbook.Worksheets(1) '读取第一个sheet页的数据
    'totalRow = ActiveSheet.Range("C" & Rows.Count).End(xlUp).Row
    'totalRow = 100
    totalRow = sheet.UsedRange.Rows.Count
    totalColumn = sheet.UsedRange.Columns.Count
    For i = 1 To totalRow
        For j = 1 To totalColumn
            Sheets("sheet1").Cells(i, j) = sheet.Cells(i, j)
        Next j
    Next i
    Workbook.Close
    MsgBox "读取成功!", vbSystemModal '读取完后弹框提醒
'----------------------------------------------
End Sub

  

posted @ 2021-08-31 15:30  糖果的二师兄  阅读(668)  评论(0编辑  收藏  举报