I am trying to find the correct VBA to add the file name to column C of several worksheets in a folder. The file name should only be added to column C for rows that have info in columns A and/or B and it can overwrite anything that is currently in column C. The VBA I am currently using works but sometimes skips row 1 or adds the file name to several rows below where there is no info in columns A & B (that I can see). This is what I am currently using -
Sub STEP_2_InsertsFileName()
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) '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
Dim i As Long
For i = 2 To Sheets(1).UsedRange.Rows.Count
Sheets(1).Range("C" & i).Value = myfile
Next i
wbk.Close savechanges:=True
myfile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = False
MsgBox "Done - move on to STEP 3"
End Sub
Sub STEP_2_InsertsFileName()
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) '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
Dim i As Long
For i = 2 To Sheets(1).UsedRange.Rows.Count
Sheets(1).Range("C" & i).Value = myfile
Next i
wbk.Close savechanges:=True
myfile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = False
MsgBox "Done - move on to STEP 3"
End Sub