Need a VBA Macro get data from one file to another + calculation

robertwp7472

New member
Joined
Jul 22, 2016
Messages
86
Reaction score
0
Points
0
Location
Fox Island, WA
I could use some help writing this Macro. Its over my head. I am building an xlsm with control buttons and I need some code that will perform the functions below. Thanks.

Step 1
I have data on one sheet called CPReport.xlsx (CP) which is a variable length sheet that changes every day. Column “B” of CP has order#s that match order#s in column “I” of my main sheet called DockSchedule.xls (DS).

What I need is VBA for my macro that compares "I" in DS to "B" in CP and if there is a match returns the value in "C" from CP to "M" in DS.

Here is some bad syntax for logic: IF(sheetDS "I" = sheet CP 'B", sheetDS "L" = sheetCP "C")

L2=VLOOKUP($I2,[CPReport.xlsx]Sheet1!$B$2:$B$200,COLUMN(3),0)

Not sure if this VLOOKUP has the correct syntax.
Step 2

The data in column “H” of DS has duplicating values called Master Ship# (MS). I want to delete the duplicate lines; however, a calculation must be performed based upon Column “I” first.

Column “I” on DS is Order# (ON); there can be multiple “ON’s” tied to the MS in “H”, the calculation that needs to be done is from numbers in Column L. These are Case Pick (CP) quantities transferred from step1.

What I need done is for the quantities in “L” to be summed IF the MS in “H” is the same. The result of the SUMIF can be put into column M if needed. Here's the tricky part that I am clueless on:

I want the rows deleted that contain the duplicate MS but I want to keep the line that has the largest value in M after the SUMIF function runs.
 
Please post your sheet with data and your macro so we can have a better view on how to help. Thx
 
Please post your sheet with data and your macro so we can have a better view on how to help. Thx

View attachment DockSchedule.xlsx
View attachment CPReport.xlsx

At this point my exposure to writing code is only HTML and Visual Basic circa 2003. I can at times decipher what has been written in VBA but struggle to write it myself.

Code:
Sub CasePicks1()
' Get Data from Source File
Dim cp1 As Workbook, cp2 As Workbook, cp2Loc As String
Dim ds2 As Worksheet, ds2Name As String

Application.ScreenUpdating = False
cp2Loc = "C:\Users\Family\My Documents\Dads\Work\Dock Schedule\CPreport.xlsx"
ds2Name = "DockSchedule"

Set cp1 = ActiveWorkbook
Set cp2 = Workbooks.Open(Filename:=cp2Loc)
Set ds2 = cp2.Sheets(ds2Name)

  [COLOR=#0000cd]  'Here is where I think I am missing the functional part
    'I bastardized the above from a previous macro in the sheet
    'I think that this will correctly call up CPreport but
    'At that point I become lost trying to write the functional code[/COLOR]

cp2.Close False
Application.ScreenUpdating = True
End Sub
 
Last edited by a moderator:
Does this do what you're after for the Step 1 requirements ?
 

Attachments

  • DockSchedule.xlsm
    46.4 KB · Views: 26
Does this do what you're after for the Step 1 requirements ?

At this point this is untested because as I said, I am assuming that this code will connect DockScedule to CPreports allowing whatever VBA script is written afterward to function. I am not even sure that the syntax for this is correct because I borrowed it from another process in the sheet which does function correctly.
 
I'm not sure your syntax is correct either, I didn't use it.

If you're not into looking at the code to see how it operates that's fine by me, but if you happen to, replace this line
Code:
Set src = srcWB.Sheets("Sheet1").Range("B4:B64")
with this
Code:
With srcWB
    lr = .Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
    Set src = srcWB.Sheets("Sheet1").Range("B4:B" & lr)
End With

Good luck with part 2.

PS: did I miss any of your cross posts ?
 
My Bad. I did not realize at first that the attached file had new code to test. I changed the line per your suggestion. Thank you; however, when I run it, nothing happens.

Shouldn't the values from CPreports column C populate into DockSchedule column L if the value in DockSchedule column I matches the value in CPreports column B?


Code:
Sub Step1()
    Dim srcWB As Workbook, strName As String, strPath As String
    Dim src As Range, rng As Range, cel As Range, fndON As Range
    Dim lr As Long
    
Application.ScreenUpdating = False

'check that source workbook is open
strName = "CPReport.xlsx"
    If IsWbOpen(strName) Then
        Set srcWB = Workbooks(strName)
    Else
        strPath = "C:\Users\Family\My Documents\Dads\Work\Dock Schedule\"
        'strPath = "D:\Forum Stuff\RobertWP\"
        Set srcWB = Workbooks.Open(strPath & strName)
    End If

With ThisWorkbook.Sheets("DockSchedule")
    lr = .Cells(Rows.Count, "I").End(xlUp).Row
    Set rng = .Range("I3:I" & lr)
End With

[COLOR=#0000cd]With srcWB
    lr = .Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
    Set src = srcWB.Sheets("Sheet1").Range("B4:B" & lr)
End With[/COLOR]

For Each cel In rng
    If cel.Value <> "" Then
        Set fndON = src.Find(What:=cel.Value, _
                             LookIn:=xlValues, _
                             LookAt:=xlWhole, _
                             SearchOrder:=xlByRows, _
                             SearchDirection:=xlNext, _
                             MatchCase:=False)
        
        If Not fndON Is Nothing Then
            cel.Offset(0, 4).Value = fndON.Offset(0, 1).Value
        End If
    End If
Next cel

srcWB.Close False

Application.ScreenUpdating = True

End Sub

Also... Both files are a new run everyday and are never the same length so row counting is dynamic.
 
Last edited:
Also... Both files are a new run everyday and are never the same length so row counting is dynamic.
that's what the change looks after. Changes the range to search from the static B4:B64 to B4 down to the last row.

when I run it, nothing happens.
Nothing happened when I used the CPreports you posted either, until I copied some of the order#s from DockSchedule and sprinkled them throughout the CPreports B column to make sure there was actually something there that did match.
 
Last edited:
that's what the change looks after. Changes the range to search from the static B4:B64 to B4 down to the last row.


Nothing happened when I used the CPreports you posted either, until I copied some of the order#s from DockSchedule and sprinkled them throughout the CPreports B column to make sure there was actually something there that did match.


Oh OK! Now I think I know what happened. It's very possible that I inadvertently used files from different dates. When I get back to work I will run fresh files and re-test. Thank you so much for you help.
 
Another revision, in your first post the verbiage as to where things go in DS said "M", I should have payed more attention after that, it's "L" . Easy fix though, change the cel.offset(0, 4) to cel.offset(0, 3)
 
Thanks. Can this part be made part of the Sub for portability or does it need to be a stand alone?

Code:
Function IsWbOpen(wbName As String) As Boolean
    'check all open workbooks for one with specific name
        Dim i As Long
    'step thru all open workbooks
    For i = Workbooks.Count To 1 Step -1
        If Workbooks(i).Name = wbName Then Exit For
    Next
    'if i reaches zero ie:False workbook wasn't found
    If i <> 0 Then IsWbOpen = True
End Function
 
Can eliminate everything and use this
Code:
Sub TransferData()
    Dim srcWB As Workbook, strName As String, strPath As String
    Dim src As Range, rng As Range, cel As Range, fndON As Range
    Dim lr As Long
    
Application.ScreenUpdating = False

'path and name for source workbook
strPath = "C:\Users\Family\My Documents\Dads\Work\Dock Schedule\"
strName = "CPReport.xlsx"

'set source
    On Error Resume Next    'disable error notification
    Set srcWB = Workbooks(strName)
    On Error GoTo 0         're-enable error notification
    'if not already open
    If srcWB Is Nothing Then
        Set srcWB = Workbooks.Open(strPath & strName)
    End If

'set what to loop through on DockSchedule
With ThisWorkbook.Sheets("DockSchedule")
    lr = .Cells(Rows.Count, "I").End(xlUp).Row
    Set rng = .Range("I3:I" & lr)
End With

'set where to find it in CPreport
With srcWB
    lr = .Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
    Set src = srcWB.Sheets("Sheet1").Range("B4:B" & lr)
End With

'do the loop and find
For Each cel In rng
    If cel.Value <> "" Then
        Set fndON = src.Find(What:=cel.Value, _
                             LookIn:=xlValues, _
                             LookAt:=xlWhole, _
                             SearchOrder:=xlByRows, _
                             SearchDirection:=xlNext, _
                             MatchCase:=False)
        
        If Not fndON Is Nothing Then    'was found
            'transfer data
            cel.Offset(0, 3).Value = fndON.Offset(0, 1).Value
        End If
    End If
Next cel

srcWB.Close False

Application.ScreenUpdating = True

End Sub
 
Thanks for you help.

I am getting a Debug screen when I run the Macro on the line with blue text. I transferred your code to my Xlsm named DSTool

Sub CPStep1()
'
' This Macro fins Case Pick Data on CPReport and transfers it to DSTool
' Originally written by www.excelguru.ca forum member NoS, British Columbia
' Thank you NoS for your help
'
Dim srcWB As Workbook, strName As String, strPath As String
Dim src As Range, rng As Range, cel As Range, fndON As Range
Dim lr As Long

Application.ScreenUpdating = False

'path and name for source workbook
strPath = "C:\Users\Family\My Documents\Dads\Work\Dock Schedule\"
strName = "CPReport.xlsx"

'set source
On Error Resume Next 'disable error notification
Set srcWB = Workbooks(strName)
On Error GoTo 0 're-enable error notification
'if not already open
If srcWB Is Nothing Then
Set srcWB = Workbooks.Open(strPath & strName)
End If

'set what to loop through on DSTool
With ThisWorkbook.Sheets("DSTool")
lr = .Cells(Rows.Count, "I").End(xlUp).Row
Set rng = .Range("I3:I" & lr)
End With

'set where to find it in CPreport
With srcWB
lr = .Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
Set src = srcWB.Sheets("Sheet1").Range("B4:B" & lr)
End With

'do the loop and find
For Each cel In rng
If cel.Value <> "" Then
Set fndON = src.Find(What:=cel.Value, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)

If Not fndON Is Nothing Then 'was found
'transfer data
cel.Offset(0, 3).Value = fndON.Offset(0, 1).Value
End If
End If
Next cel

srcWB.Close False

Application.ScreenUpdating = True

End Sub

I am running my Macros from Personal.xlsb, rather than ThisWorkbook... Could that be the issue?
 
I am running my Macros from Personal.xlsb, rather than ThisWorkbook... Could that be the issue?
Yes. ThisWorkbook always refers to the one the code is in. Will now require using a Set statement.

Please verify:

The source location folder is C:\Users\Family\My Documents\Dads\Work\Dock Schedule
The source workbook name is CPReport.xlsx
The source sheet name is "Sheet1"

The destination location folder is.... ?
The destination workbook name is... ? originally was DockSchedule.xls
The destination sheet name is... ? originally was "DockSchedule"
 
The destination location folder is.... ? C:\Users\Family\My Documents\Dads\Work\Dock Schedule
The destination workbook name is... ? originally was DockSchedule.xls Is now Sup-DSTool.xlsm
The destination sheet name is... ? originally was "DockSchedule" Is now DSTool

Also, you had said that you had to sprinkle CPReport with data from DockSchedule to make the Macro work; however, upon visual check of the files I have there are multiple instances of matching data. Could it be possible that because these originally are data dumps from SAP that they are formatted as text and not numbers or would that not matter?
 
OK, think I've got it now, try this
Code:
Sub CPStep1()

    Dim srcWB As Workbook, dstWB As Workbook
    Dim strPath As String, srcName As String, dstName As String
    Dim src As Range, rng As Range, cel As Range, fndON As Range
    Dim src_lr As Long, dst_lr As Long, Pick As Long
    
Application.ScreenUpdating = False

'path and name for workbooks
strPath = "C:\Users\Family\My Documents\Dads\Work\Dock Schedule\"
srcName = "CPReport.xlsx"
dstName = "Sup-DSTool.xlsm"

'set source
    On Error Resume Next    'disable error notification
    Set srcWB = Workbooks(srcName)
    On Error GoTo 0         're-enable error notification
    'if not already open
    If srcWB Is Nothing Then
        Set srcWB = Workbooks.Open(strPath & srcName)
    End If

'set destination
    On Error Resume Next    'disable error notification
    Set dstWB = Workbooks(dstName)
    On Error GoTo 0         're-enable error notification
    'if not already open
    If dstWB Is Nothing Then
        Set dstWB = Workbooks.Open(strPath & dstName)
    End If

'set what to loop through on DSTool
    With dstWB.Sheets("DSTool")
    dst_lr = .Cells(Rows.Count, "I").End(xlUp).Row
    Set rng = .Range("I3:I" & dst_lr)
    End With

'set where to find it in CPreport
    With srcWB
    src_lr = .Sheets("Sheet1").Cells(Rows.Count, 2).End(xlUp).Row
    Set src = srcWB.Sheets("Sheet1").Range("B4:B" & src_lr)
    End With

'do the loop and find
    For Each cel In rng
        If cel.Value <> "" Then
            Set fndON = src.Find(What:=CDbl(cel.Text), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)
            
            If Not fndON Is Nothing Then 'was found
                'transfer data
                Pick = Trim(fndON.Offset(0, 1).Value)
                cel.Offset(0, 3).Value = Pick
            End If
        End If
    Next cel

'close the source
    srcWB.Close False

    Set srcWB = Nothing
    Set dstWB = Nothing
    
Application.ScreenUpdating = True

End Sub

Based on the 2 example files you've posted, here's a pic of what I end up with in print pre-view after Step 2.
attachment.php

Can you confirm that this would be right?
Also read this http://www.excelguru.ca/content.php?184
 

Attachments

  • Microsoft Excel - Sup-DSTool.jpg
    Microsoft Excel - Sup-DSTool.jpg
    82.9 KB · Views: 27
If that's what happens when you run the Macro then yes. That looks absolutely correct. I will verify and let you know if I get any Bugs. I don't think I will.
 
Getting a Bug

I ran the Macro and I am getting a Bug. It says there is a Type mis-match
 

Attachments

  • Debug Scrn.jpg
    Debug Scrn.jpg
    64.7 KB · Views: 9
I figured out the type mis-match thing. My version of the form in DS-Tool starts on row 7 So I changed the I3:I below to I7:I.
Set rng = .Range("I3:I" & dst_lr)

But now I am back to getting no result again as if it is not finding a match to "I" in "B" of CPReport :Cry:. ??????? As I mentioned in a previous post, I did a visual comparison and there are matches all over I am not sure why it's not picking them up.
 
NoS,
I am also looking at the code and wandering which command is giving the instruction to put result in Column K. It's probably right in front of my face I am just not able to see it.
 
Back
Top