Advanced/Complex VBA Help!

im2bz2p345

Board Regular
Joined
Mar 31, 2008
Messages
229
I have the following code, but need some changes made to it:

Rich (BB code):
Option Explicit
 
Private Sub ProcessMatchedFile(ByVal sFileName As String)
Dim num As Variant, _
 LR As Long, _
 target As String, _
 cashflowamt As Long, _
 XLSFile As Workbook
 
MsgBox sFileName
 'do somethin with any matching files
    Set XLSFile = Workbooks.Open(sFileName)
    target = "Pre-tax Cash Flow"
    LR = Range("B" & Rows.Count).End(xlUp).Row
'Find the row the string "Pre-tax Cash Flow" appears on.
    num = Application.Match("*" & target & "*", Range("B1:B" & LR), 0)
'If no match is found with wildcards, the next match will search for when the string "Pre-tax Cash Flow" is the only thing in the cell.
    If IsError(num) Then
        num = Application.Match(target, Range("B1:B" & LR), 0)
    End If
'If the string is found, continue with code.
    If Not IsError(num) Then
 
 'Copies cashflow amount from source file
            cashflowamt = Range("C" & num).Offset(0, 1).Value
'Pastes the cashflow amount for the appropriate BU in the master file
            cashflowamt.Copy Destination:=ThisWorkbook.Sheets("All Regions_Detail").Range("AL" & BUrow)
    End If
End Sub

 
Private Function DirectoryListToArray(ByVal sSourceFolder As String, FileAry() As String) As Boolean
  Dim objFSO As FileSystemObject
  Dim objFile As File
  Dim lNum As Long
   
  DirectoryListToArray = False
  On Error GoTo QuickExit
  
  If sSourceFolder = "" Then Exit Function
  
  Set objFSO = New FileSystemObject
   
  With Application.FileSearch
    .LookIn = sSourceFolder
    .FileType = msoFileTypeAllFiles
    'search sub directories if required
    .SearchSubFolders = False
    .Execute
    
    Erase FileAry
    
    lNum = 0
    If .FoundFiles.Count > 0 Then
      For lNum = 1 To .FoundFiles.Count
        Set objFile = objFSO.GetFile(.FoundFiles(lNum))
        ReDim Preserve FileAry(lNum)
        'if you searched sub-folders as well, will need to play with the objFile.Path to qualify the file name
        FileAry(lNum) = objFile.Name
      Next
    End If
  End With
   
  Set objFile = Nothing
  Set objFSO = Nothing
  
  If lNum > 0 Then DirectoryListToArray = True
  
QuickExit:
  On Error GoTo 0
End Function

Private Function GetFolderName() As String
  Dim MonthNumber As String
  Dim MonthAbbreviation As String
  
  If IsDate(ThisWorkbook.Sheets("All Regions_Detail").Range("AM1")) Then
    MonthNumber = Format(Month(ThisWorkbook.Sheets("All Regions_Detail").Range("AM1").Value), "00")
    MonthAbbreviation = MonthName(MonthNumber, True)
  End If
  GetFolderName = "O:\Shared Svcs Acctg\_Close 2011\All\" & MonthNumber & _
                  " " & MonthAbbreviation & "\ROIC Calculation\"
End Function

Sub LocateMatchingFiles()
  Dim lNum As Long
  Dim FAry() As String
  Dim sPath As String
  
  'get the source folder name
  sPath = GetFolderName
  
  'get the array containing the list of files in the source folder
  'if this returns FALSE, no files were found or there was an error
  If DirectoryListToArray(sPath, FAry) Then
    For lNum = LBound(FAry) To UBound(FAry)
      'here determine if the partial string "XYZ" is contained in the file name
      'change "XYZ" to whatever needs to be matched
      If InStr(1, FAry(lNum), "XYZ", vbTextCompare) > 0 Then
        'found a natching filename - now process it
        'add the source folder name if you need to do something with the path and file
        'make sure there is a "\" on the end of the path name for this to work
        ProcessMatchedFile sPath & FAry(lNum)
      End If
    Next
  End If
  
  Erase FAry
End Sub

#1) Instead of specifying "XYZ" as the value to search for, is it possible to run this exact code for ALL the business units (Column A) in my master file (here is a screenshot of it: http://ploader.net/files/f2f6fbc15e328ef4be11dcdcec763bc7.png). So basically a loop would be created, it would look at the 1st business unit in Column A, find the file in the directory, open it, do some actions (ProcessMatchedFile), then move onto the 2nd business unit in Column A, open it, do some actions (ProcessMatchedFile), and so forth...

#2) I'm just having a bit of trouble now doing a series of actions on the source file (in the ProcessMatchedFile). Here is a sample of how a source file looks: http://ploader.net/files/c6a256d09b0faebb5b07173b48487bee.png

I want this to get the value next to words "Pre-tax Cash Flow" in my source file and paste it back into my master file in the appropriate BU's file (that was opened). The parts highlighted in red are the ones that I am not sure how to get.

Hopefully this makes sense. Please feel free to clean up or optimize any code as you see fit (I'm very new to VB coding, so still struggling to do basic things). Let me know if you have any questions or need further clarification.

~ Im2bz2p345 :)
 

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.
Norie had mentioned that my previous code has "unqualified reference" such as Match in this thread: http://www.mrexcel.com/forum/showthread.php?p=2681740#post2681740

I'm not sure if that can be resolved with this new code.

Also, I looked that the syntax for the "Cells.Find" method, which might work better than Application.Match method, as Norie mentioned.

Here it is:
Code:
Cells.Find(What:="Pre-tax Cash Flow", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate

Please help with this code if you can!

~ Im2bz2p345 :)
 
Upvote 0
Below is an example of using FoundCell - google it and you will different examples of how use this function


Code:
    Dim Rangeval As String
    Dim FoundCell As Range
    Dim LastCell As Range
    With ActiveSheet.UsedRange
        ColLast = .Columns(.Columns.Count).Column
        LastRow = .Rows(.Rows.Count).Row
    End With
    Rangeval = "A1:" & Split(Cells(1, ColLast).Address, "$")(1) & LastRow
    With Range(Rangeval)
        Set LastCell = .Cells(.Cells.Count)
    End With
    Set FoundCell = Range(Rangeval).Find(What:=("Pre-tax Cash Flow"), after:=LastCell)
    If FoundCell Is Nothing Then
                [COLOR=red]your code[/COLOR]
           Else
                [COLOR=red]your code[/COLOR]
    End if
 
Last edited:
Upvote 0
Below is an example of using FoundCell - google it and you will different examples of how use this function


Code:
    Dim Rangeval As String
    Dim FoundCell As Range
    Dim LastCell As Range
    With ActiveSheet.UsedRange
        ColLast = .Columns(.Columns.Count).Column
        LastRow = .Rows(.Rows.Count).Row
    End With
    Rangeval = "A1:" & Split(Cells(1, ColLast).Address, "$")(1) & LastRow
    With Range(Rangeval)
        Set LastCell = .Cells(.Cells.Count)
    End With
    Set FoundCell = Range(Rangeval).Find(What:=("Pre-tax Cash Flow"), after:=LastCell)
    If FoundCell Is Nothing Then
                [COLOR=red]your code[/COLOR]
           Else
                [COLOR=red]your code[/COLOR]
    End if

I am not really sure how this helps me Rasm.

My 1st request was regarding creating a loop so that this code could be ran automatically for all business units in my master files.

My 2nd request was trying to copy a particular value from my source file (is my code incorrect?) and pasting that value back into my master file, but in the appropriate place based on the business unit.

~ Im2bz2p345 :)
 
Upvote 0
This should allow loop of the sheets in the workbook just opened - you can add the workbookName in front - hope this helps

Code:
For i = 1 To Worksheets.Count
        With Worksheets(Worksheets(i).Name)
            MsgBox "your code   " & Worksheets(i).Name
        End With
Next i
 
Upvote 0
im2bz2p345

I'm getting confused here - why have you started another new thread?
 
Upvote 0
Here is an example of copy paste from one sheet to another - you will have to set that ranges to suit your needs - again if you copy from one workbook to another - then you have to also use the workbook name - hope this helps

Code:
    Dim RangeSource As String
    Dim RangeDestination As String
    RangeSource = "A1:A5"
    RangeDestination = "B1:B5"
    Worksheets("NameOfSendingSheet").Range(RangeSource).Copy
    Worksheets("NameOfReceivingsheet").Paste Destination:=Worksheets("NameOfReceivingsheet").Range(RangeDestination)
 
Upvote 0
Thank you Rasm! I know you posted about a simple copy-paste from one sheet to another, but my scenario is a bit more complex. I need to be able to copy from one workbook, then paste in another workbook, but at a specific place (I can't just specify a range like in your example). It need to be able to "lookup" where the BU is and paste on that row.


im2bz2p345
I'm getting confused here - why have you started another new thread?

My other thread (http://www.mrexcel.com/forum/showthread.php?p=2682518) was using a different set of code and I had posted that just to overcome the errors.

Anyway, I think that I will continue at the other thread and just say that I don't wish to run a loop for every business unit anymore. I think it will be easier for me to create a macro for each individual business unit and run it one at a time.

Thank you guys for the help!

~ Im2bz2p345 :)
 
Upvote 0
No problem - but between these bits & pieces you can write a piece of code that will do exactly what you want - I simply hardcoded the ranges as an example.
 
Upvote 0

Forum statistics

Threads
1,224,600
Messages
6,179,836
Members
452,947
Latest member
Gerry_F

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