Link to home
Start Free TrialLog in
Avatar of stmoritz
stmoritz

asked on

Run Excel VBA code on all files in a folder except one (the one with the code)

I am looking to change the following code as follows:

Currently, the active workbook where the code is run from is the target workbook that fetches data from the source workbook C:\!ee\AgreementBase\ee_company_details_BANANA.xls

Now the code should be changed so that it processes any file in this folder except the target file. So there might be twenty others like ee_company_details_APPLE.xls, ee_company_details_ORANGE.xls etc. and the data from these sheets should all be added in the same way like the BANANA one...
Sub FetchDataFromIndividualFilesToDb()

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.AutomationSecurity = msoAutomationSecurityLow

'dim the variables
Dim ActiveCompany As String, ActiveCompanyRowInDb As Integer, LastRowAgreementDb As Integer, ActiveCompanyRow As Integer, LastColTargetWs As Integer

'dim the ranges
Dim TargetRange As Range, SourceRange As Range, SortRange As Range, SourceCompanyCodeRange As Range, TargetCompanyCodeRange As Range

'dim the workbooks
Dim TargetWb As Workbook, SourceWb As Workbook

'dim the worksheets
Dim TargetWs As Worksheet, SourceWs As Worksheet

'set and open workbooks
Set TargetWb = ActiveWorkbook
Set SourceWb = Workbooks.Open("C:\!ee\AgreementBase\ee_company_details_BANANA.xls")
'Set TargetWb = Workbooks("ee_agreement_base.xls")


'set worksheets
Set TargetWs = TargetWb.Sheets("AgreementData")
Set SourceWs = SourceWb.Sheets("CompanyData")

'activate SourceWb
SourceWb.Activate

'get Company Code to process
ActiveCompany = SourceWs.Range("B41").Value
If ActiveCompany = "" Then
                  TargetWb.Close False
                  Exit Sub
End If
'ActiveCompanyRow = ActiveCell.Row

'ask whether to send this Company to db
OverWrite = MsgBox("Add data for " & ActiveCompany & " to ee_agreement_base.xls?", vbYesNo)
            If OverWrite = vbNo Then Exit Sub

'activate TargetWb
TargetWb.Activate

'get last non-empty row in TargetWs
With TargetWs
    .Select
    .Range("A1").Select
End With
LastRowAgreementDb = Cells(Rows.Count, ActiveCell.Column).End(xlUp).Row

'search for the Company code in TargetWs
For i = 1 To LastRowAgreementDb
    If TargetWs.Range("A" & i).Value = ActiveCompany Then Exit For
Next
TargetCompanyRow = i

'set source and target range
Set SourceRange = SourceWs.Range("D2:D38")
Set SourceCompanyCodeRange = SourceWs.Range("B41")
Set TargetCompanyCodeRange = TargetWs.Range("A" & TargetCompanyRow)
Set TargetRange = TargetWs.Range("B" & TargetCompanyRow & ":AL" & TargetCompanyRow)

'overwrite company code in target ws
TargetCompanyCodeRange = SourceCompanyCodeRange.Value

'copy paste company data to target ws
SourceWs.Activate
SourceRange.Select
    Selection.Copy
    TargetWs.Activate
    TargetRange.Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=True
Application.CutCopyMode = False

'get last column
TargetWs.Activate
LastColTargetWs = Cells(1, Columns.Count).End(xlToLeft).Column

'sort agreement db alphabetically
If TargetCompanyRow > LastRowAgreementDb Then
   Set SortRange = TargetWs.Range(TargetWs.Cells(2, 1), TargetWs.Cells(TargetCompanyRow, LastColTargetWs))
       Else: Set SortRange = TargetWs.Range(TargetWs.Cells(2, 1), TargetWs.Cells(LastRowAgreementDb, LastColTargetWs))
End If
   
SortRange.Sort Key1:=Range("A2"), Order1:=xlAscending, Header:=xlNo
Range("A" & LastRowAgreementDb).Select

'close SourceWb
SourceWb.Close False

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = True
Application.AutomationSecurity = msoAutomationSecurityByUI
End Sub

Open in new window

ee-agreement-base.xls
ee-company-details-BANANA.xls
ASKER CERTIFIED SOLUTION
Avatar of Arno Koster
Arno Koster
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of stmoritz
stmoritz

ASKER

Thanks akoster.

Before I check a quick ignorant question (forgive me):

could I change
activeFile = dir("C:\!ee\AgreementBase\*.xls")

Open in new window

to
activeFile = dir("C:\!ee\AgreementBase\ee_agreement_base*.xls")

Open in new window


What I don't see is how this change would now for example process all the ee_agreement_base".xls in that folder one after the other, I mean I see no loop or so... shall I just test it?
sorry. should read:

What I don't see is how this change would now for example process all the ee_agreement_base*.xls in that folder one after the other, I mean I see no loop or so... shall I just test it?

(* instead of " is correct)
no need to ask for forgiveness !

that would indeed be no problem at all, then you would only act on excel files starting with ee_agreement_base.

The finesse is in the use of the DIR statement.

If you are not confortable using it, try running this small macro :
sub test_dir_function()
dim result as string

   result = dir("C:\!ee\AgreementBase\ee_agreement_base*.xls")
   while result <> ""
      msgbox result
      result = dir
   wend

Open in new window


it will find all ee_agreenent_base excel files and display their names with message boxes.
sorry. my post was erroneus. should of course be

activeFile = dir("C:\!ee\AgreementBase\ee_company_details_*.xls")

Open in new window


will check now how it works...
i get the following error, although the file is there...??
screenshot.jpg
Avatar of Rory Archibald
(NFP)
Dir only returns the filename, so you have to add the path on when using Workbooks.open
thanks rorya. again, I didn't read the helping expert answers carefully. you pointed me at this again.

I think I didn't incorporate ID: 35425041:
Set SourceWb = Workbooks.Open("C:\!ee\AgreementBase\" & activefile)
thank you very much!