Code To Open Files Within Folder Make Changes And Close

Dazzawm

Well-known Member
Joined
Jan 24, 2011
Messages
3,748
Office Version
  1. 365
Platform
  1. Windows
I need a code that will open dozens of files within a folder in my desktop and if what is found in column A in the active sheet in column AG in each file then it needs to be changed to what is in column B as below. Thanks

Excel 2010
AB
1Column AGChanges To
2CentreCentre
3Centre-LHLH Centre
4Centre-RHRH Centre
5FRFR
6FR Inner-LHFR LH Inner
7FR Inner-RHFR RH Inner
8FR Lower-LHFR LH Lower
9FR Lower-RHFR RH Lower
10FR Outer-LHFR LH Outer
11FR Outer-RHFR RH Outer
12FR UpperFR Upper
13FR Upper-LHFR LH Upper
14FR Upper-RHFR RH Upper
15FR-DSFR DS
16FR-InnerFR Inner
17FR-LHFR LH
18FR-OuterFR Outer
19FR-PSFR PS
20FR-RHFR RH
21InnerInner
22Inner-LHLH Inner
23Inner-RHRH Inner
24LHLH
25OuterOuter
26Outer-LHLH Outer
27Outer-RHRH Outer
28RHRH
29RRRR
30RR Inner-LHRR LH Inner
31RR Inner-RHRR RH Inner
32RR LH+RHRR LH+RH
33RR-InnerRR Inner
34RR-LHRR LH
35RR-OuterRR Outer
36RR-RHRR RH

<colgroup><col style="width: 25pxpx"><col><col></colgroup><thead>
</thead><tbody>
</tbody>
Sheet1
So looking at row 3 if Centre-LH is found in column AG of any of the files then it needs to change it to LH Centre, save and close each file and so on...
 
Last edited:

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
If it helps this is a code that opens all the files and clears contents of column AG. Maybe someone could adapt it for me as it has the same path.

Code:
Sub OpenAndClearContentsInColumnAG()


Dim strF As String, strP As String
Dim wb As Workbook
Dim ws As Worksheet


'Edit this declaration to your folder name
strP = "C:\Documents and Settings\MANAGER\Desktop\Darrens Catalogues"


strF = Dir(strP & "\*.xlsm") 'Change as required


Do While strF <> vbNullString


    Set wb = Workbooks.Open(strP & "\" & strF)
    Set ws = wb.Sheets(1) 'uses first sheet or if all the same names then ws.Sheets("yoursheet")
    ws.Range("AG2:AG" & ws.Range("AG" & ws.Rows.Count).End(xlUp).Row).ClearContents
    wb.Close True
    
    strF = Dir()
Loop


End Sub
 
Upvote 0
I got it working with this. I set up the 'worker' sheet with a sheet called Lookup that contained all the information in the first post and then ran this macro. This allows the user to select a number of files rather than hard-coding it in.
Code:
Option Explicit

Sub CheckSheets()

    Dim fDialog         As Office.FileDialog
    Dim varFile         As Variant
    Dim wb              As Workbook
    Dim ws              As Worksheet
    Dim lookupRange     As Range
    Dim newRange        As Range
    Dim thisCell        As Range
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    
    Set lookupRange = ThisWorkbook.Sheets("LookUp").Range("A1:A36")     'Set as you see fit
    Set newRange = ThisWorkbook.Sheets("LookUp").Range("B1:B36")         'Set as you see fit
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
    With fDialog
        .AllowMultiSelect = True
        .Title = "Import Files"
        .Filters.Clear
        .Filters.Add "Excel Documents", "*.xlsx"
        .Filters.Add "Excel Macro Documents", "*.xlsm"
        .Filters.Add "All Files", "*.*"
    End With
    
    If fDialog.Show Then
    'Check for cancel
        
        For Each varFile In fDialog.SelectedItems
    
            Set wb = Workbooks.Open(varFile)
            Set ws = wb.Sheets(1) 'uses first sheet or if all the same names then ws.Sheets("yoursheet")
            
            For Each thisCell In ws.Range("AG2:AG" & ws.Range("AG" & ws.Rows.Count).End(xlUp).Row)
            
                On Error Resume Next
                If Not IsError(Application.WorksheetFunction.Match(thisCell.Value, lookupRange, 0)) Then
                
                    thisCell.Value = Application.WorksheetFunction.Index(newRange, Application.WorksheetFunction.Match(thisCell.Value, lookupRange, 0))
                
                End If
                On Error GoTo 0
            
            Next thisCell
            
            Application.Calculate
            wb.Close True
        
        Next varFile
    
    End If

    Application.Calculation = xlCalculationSemiautomatic
    Application.ScreenUpdating = True

End Sub

Hope that helps.

/AJ
 
Upvote 0
Thanks Adam, wheres the part where it has the location of the folder that contains all the files?
 
Upvote 0
When you run it, you'll be presented with a file selection dialog box, you can select one or more files from there; rather than hard-coding in the file locations.

/AJ
 
Upvote 0
It worked and it didn't! It opened and closed all the files but didn't seem to make any changes. Although they all say 'last modified' a few mins ago?

I don't know if it makes a difference but a lot of the rows in column AG will be blank. Should the row count bit be changed to column C as there will always be something in there?
 
Last edited:
Upvote 0
It worked and it didn't! It opened and closed all the files but didn't seem to make any changes. Although they all say 'last modified' a few mins ago?

I don't know if it makes a difference but a lot of the rows in column AG will be blank. Should the row count bit be changed to column C as there will always be something in there?

That might be wise. Does it make it work?

/AJ
 
Upvote 0
I didn't work as expected, I will be back Tuesday when I'm back to work with an update.

Thanks Adam.
 
Upvote 0
I have tried it again and it says subscript out of range?
 
Upvote 0
Dazza,

As per your PM request I have taken a look at this as Adam is offline for a while.

Firstly, this requires that you have the code in the module of a sheet named 'Lookup' and that your 'before' and 'after' strings are in columns A and B respectively.
I would suggest that you have no other data on that sheet**
The code will look at the first sheet only, index(1), of the file to be converted.

I suspect that your subscript out of range error may be that you do not have sheet 'Lookup' ???


The ranges for before and after in the code extend down to row 36 as per your post #1.. If any different then you must edit them to suit.
I have changed the column that determines the last row to be C as per your post #7.

With that done, Adam's code made the necessary changes, in the file selected via the file dialog, when I tested it!!!

**Re your request to log any strings that are not matched. If I understand what you want correctly then my revised code will create a new column in the Lookup sheet for every other file that you open for conversion.
It will mark '***' for each of the strings found somewhere in AG and will leave blank if a lookup string is not found anywhere in AG of the conversion file.


Excel 2007
ABCD
1Column AGChanges ToDazza.xlsxDazza2.xlsx
2CentreCentre******
3Centre-LHLH Centre******
4Centre-RHRH Centre******
5FRFR******
6FR Inner-LHFR LH Inner******
7FR Inner-RHFR RH Inner******
8FR Lower-LHFR LH Lower***
9FR Lower-RHFR RH Lower***
10FR Outer-LHFR LH Outer***
11FR Outer-RHFR RH Outer***
12FR UpperFR Upper******
13FR Upper-LHFR LH Upper******
14FR Upper-RHFR RH Upper******
15FR-DSFR DS******
16FR-InnerFR Inner******
17FR-LHFR LH******
18FR-OuterFR Outer******
19FR-PSFR PS******
20FR-RHFR RH******
21InnerInner******
22Inner-LHLH Inner***
23Inner-RHRH Inner***
24LHLH***
Lookup

Code:
Sub CheckSheets()


    Dim fDialog         As Office.FileDialog
    Dim varFile         As Variant
    Dim wb              As Workbook
    Dim ws              As Worksheet
    Dim lookupRange     As Range
    Dim newRange        As Range
    Dim thisCell        As Range
    Dim r               As Long
    Dim lstCol          As Long
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    
    Set lookupRange = ThisWorkbook.Sheets("LookUp").Range("A1:A36")     '*****Set as you see fit
    Set newRange = ThisWorkbook.Sheets("LookUp").Range("B1:B36")         '*****Set as you see fit
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
    With fDialog
        .AllowMultiSelect = True
        .Title = "Import Files"
        .Filters.Clear
        .Filters.Add "Excel Documents", "*.xlsx"
        .Filters.Add "Excel Macro Documents", "*.xlsm"
        .Filters.Add "All Files", "*.*"
    End With
    
    If fDialog.Show Then
    'Check for cancel
        
        For Each varFile In fDialog.SelectedItems
        
            lstCol = Cells(1, Columns.Count).End(xlToLeft).Column + 1
    
    
            Set wb = Workbooks.Open(varFile)
            Set ws = wb.Sheets(1) '*****  uses first sheet or if all the same names then ws.Sheets("yoursheet")
            Cells(1, lstCol) = wb.Name
            For Each thisCell In ws.Range("AG2:AG" & ws.Range("C" & ws.Rows.Count).End(xlUp).Row)   '*****Set as you see fit  Column C
            r = 0
                On Error Resume Next
                r = Application.WorksheetFunction.Match(thisCell.Value, lookupRange, 0)
                On Error GoTo 0
                If r > 0 Then
                     thisCell.Value = Application.WorksheetFunction.Index(newRange, r)
                     '**** Mark the lookup range as having been found in AG
                     If Application.WorksheetFunction.Index(lookupRange.Offset(0, lstCol - 1), r, 1) = "" Then _
                        Application.WorksheetFunction.Index(lookupRange.Offset(0, lstCol - 1), r, 1) = "***"
                End If
        
            Next thisCell
            
            Application.Calculate
            wb.Close True
        
        Next varFile
    
    End If


    Application.Calculation = xlCalculationSemiautomatic
    Application.ScreenUpdating = True


End Sub
Hope that helps.
 
Upvote 0

Forum statistics

Threads
1,214,661
Messages
6,120,790
Members
448,994
Latest member
rohitsomani

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top