打开多个Excel文件并添加新单元格

时间:2019-02-01 20:57:39

标签: excel vba

我正在尝试打开多个Excel文件,并为每个文件添加相同名称的相同新单元格。它们位于文件夹... / desktop / excel中,名称为workbook1,workbook2等。

我已经尝试过this article,但遇到运行时错误76'找不到路径'。

screenshot

我是VBA的超级新手,我们将为您提供任何帮助!这是我正在运行的脚本:

Sub LoopThroughFolder()

Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\Users\shaye\Desktop\excel" 'Your Directory
MyFile = Dir(MyDir & "*.xlsx")    'Your excel file extension
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0

Do While MyFile <> ""
    Workbooks.Open (MyFile)
        Range("G1").Value = "NewColumn" 'New Column Name
        ActiveWorkbook.Save
        ActiveWorkbook.Close True
    MyFile = Dir()
Loop

End Sub

[desktop error3]

1 个答案:

答案 0 :(得分:1)

尝试此代码。我认为您需要在目录中使用此“ \”和“ ??”在文件扩展名中找到几种excel类型

Sub LoopThroughFolder()

Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\Users\shaye\Desktop\excel\" 'Your Directory need this "\"
MyFile = Dir(MyDir & "*.xl??")    'Your excel file extension
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0

Do While MyFile <> ""
    Workbooks.Open (MyFile)
        Range("G1").Value = "NewColumn" 'New Column Name
        ActiveWorkbook.Save
        ActiveWorkbook.Close True
    MyFile = Dir()
Loop

End Sub