我做了下面的VBA代码,想法是首先遍历一个包含CSV文件的整个文件夹,然后在每个CSV文件中的A1单元格中插入一个来自“主”文件的值,宏就是从这个主文件中运行的。代码如下所示。
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder & "*.csv", vbNormal) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> ""
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(Filename:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Windows("master.xlsm").Activate
Dim c As Range
For Each c In ActiveSheet.Range("A1:A2000")
wbk.Activate
Sheets(1).Range("a1").Value = c
wbk.Close savechanges:=True
Exit For
Next
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
我按照宏的逐步过程进行操作,问题似乎来自此块
Windows("master.xlsm").Activate
Dim c As Range
For Each c In ActiveSheet.Range("A1:A2000")
wbk.Activate
Sheets(1).Range("a1").Value = c
wbk.Close savechanges:=True
Exit For
Next
由于某种原因,宏只是复制了所有CSV文件中主文件的第一个值...这很可能是一个很容易解决的问题,但我对VBA的了解很少,我找不到使其工作的方法。
感谢您的建议或帮助。
1条答案
按热度按时间qncylg1j1#
循环访问文件以写入文件
快速修复