Match and Modify serial number data using VBA

Carlit007

New Member
Joined
Sep 5, 2018
Messages
47
Office Version
  1. 2019
  2. 2016
  3. 2013
Platform
  1. Windows
  2. MacOS
Hi I am trying to find out if there's a way to do the following using VBA

I have a workbook with data from a report like the one below consisting of equipment serial numbers
The Items Highlighted in blue are Serial numbers for equipment I have in different locations

EXCEL SCREENSHOT  1.JPG


worksheet 2 has the Serial numbers I constantly track on Colum A, followed by the location on Colum J
LOCATION DATA.JPG


what I would like is for the data imported from a new report in worksheet 1 to find and match the serial number by looking at worksheet 2 and basically adding the location information from colum j right next to the Serial number all in worksheet 1 I have done this in the past by doing vlookup but it is very time consuming as I have to paste the formula right next to an empty cell next to the Serials numbers. what is the best way to go about this thanks in advance
 
You can just comment out or delete Sheet1.Activate and change Sheet1.UsedRange to ActiveSheet.UsedRange

You have to remember to run the macro with the correct Worksheet selected then, of course.
 
Upvote 0

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
@kennypete that did the trick thanks!
on the flip-side what line would you add to affect every sheet in the workbook except for the sheet2 which contains locations data
 
Upvote 0
The modified "V4" code will do that:

VBA Code:
Sub subAddLocationsV4()
    ' The Serial Numbers are unique primary keys. In this case, because there's
    ' a known fixed number of them, I've used an array to store those keys.
    Dim aKeys As Variant
    aKeys = Sheet2.Range("A2:A8").Value
    ' The corresponding items are the locations. For each of the Serial Number keys
    ' store the locations in the same position in another array.
    Dim aItems As Variant
    aItems = Sheet2.Range("D2:D8").Value
    ' Declaring "i" as an integer for doing the loops
    Dim i As Integer
    ' Loop through all the Worksheets in the Workbook EXCEPT Sheet2
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name <> "Sheet2" Then
            ws.Activate
            ' In case you have leftover formatting in the Replace dialog box from previous
            ' searches, this clears it
            Application.FindFormat.Clear
            Application.ReplaceFormat.Clear
            ' Loop from 1 to the number of (i.e. count of) the aKeys array. This is because
            ' we need to replace for every Serial Number
            For i = 1 To UBound(aKeys)
                ' Search for the Serial number. Because of the way the array aKeys is created it
                ' creates a 2D array, with the Serial numbers being in #1 of the second dimension
                ' e.g. 4THGPL2 is in aKeys(1, 1), 700GPL2 in aKeys (2, 1) and so on. The find text
                ' is the key, e.g. aKeys(1, 1) / 700GPL2, the replace text is that plus a space
                ' plus the item fron the Location array, so, e.g. aItems(1, 1)  / NGMANB301E80013
                ' (SJ) RM 211 (DESK 2). You also need to ensure that the whole cell is searched
                ' because in your example screenshot that is how they appeared.
                Cells.Replace What:=aKeys(i, 1), Replacement:=aKeys(i, 1) & " " & aItems(i, 1), _
                    LookAt:=xlWhole, SearchOrder:=xlByRows
            Next
            ' The next step is to loop through the used range of Sheet 1 and apply the
            ' formatting. Three variables are used: one for the first address of where the
            ' Serial Number being looked for appears, one for the address as a string, and
            ' the third, c, a range (i.e. in this case used for a cell address
            Dim fAddress As String, sAddress As String, c As Range
            ' Loop (as above)
            For i = 1 To UBound(aKeys)
                ' Limits the work to the used range of Sheet1
                With ws.UsedRange
                    ' Find the aKeys(i, 1), so for aKeys(1, 1) that's 4THGPL2, in
                    ' any values of the cells in the used range and because those cells
                    ' now have the location data also included within them the search needs
                    ' to be for where it appears in *part* of the cell
                    Set c = .Find(aKeys(i, 1), LookIn:=xlValues, LookAt:=xlPart)
                    ' If there is a cell with the aKeys(i, 1) then set the first address
                    ' to the address of that cell
                    If Not c Is Nothing Then
                        fAddress = c.Address
                        Do
                            ' Set that address to the string variable sAddress so that
                            ' it can be passed to the "With" that follows
                            sAddress = c.Address
                            ' Literally activate that found cell because we are now wanting
                            ' to apply formatting to an active cell. Normally you don't need
                            ' to select/activate cells, though I'm unsure whether there's any
                            ' way not to in this case of applying *partial* cell formattng.
                            Range(sAddress).Activate
                            ' Apply only Bold+Blue, noting that VBA has a constant vbBlue for
                            ' blue, but this could be a number also representing any "blue"
                            ' colour if the 'default' one is not wanted. Apply it only after the
                            ' text where the Serial Number is appearing, so FROM Len(gth) of aKeys(i, 1)
                            ' plus 1 for the space character that was added TO the end (i.e. the
                            ' Len(gth) of the entire range, which is the cell located at sAddress
                            With ActiveCell.Characters(Len(aKeys(i, 1)) + 1, Len(Range(sAddress).Value)).Font
                                .FontStyle = "Bold"
                                .Color = vbBlue
                            End With
                            ' Now loop to see whether there are any more of that Serial Number
                            Set c = .FindNext(c)
                        ' And if there are do this again, otherwise we've found all of the Serial Numbers
                        ' in that range.
                        Loop While Not c.Address = fAddress
                    End If
                End With
            ' Do the next Serial Number
            Next i
        End If
    Next
End Sub
 
Upvote 0
It worked for the entire worbook but unfortunately Worksheet2 also was affected and was not excluded from this macro
was the following code supposed to prevent this?
VBA Code:
If ws.Name <> "Sheet2" Then
            ws.Activate
 
Upvote 0
Yes, and it works provided your Worksheet is named Sheet2
1583000805199.png


My guess is you have something like
1583000909767.png


In which case either change the "Sheet2" in the code to your Worksheet's Name (in this example, "Serials") or otherwise the code could be changed to use the object.
 
Upvote 0
To elaborate:
1583039330825.png

(noting I renamed the Worksheets to make it more obvious)

This line could be modified to be doubly-sure the replacements do not happen within the "Serials" (named) Worksheet or the Worksheet with the CodeName "Sheet2".
VBA Code:
        If (ws.Name <> "Serials" And ws.CodeName <> "Sheet2") Then
This would mean that the macro would still work fine regardless of what the ws.Name is (which can happen, of course, when a user decides they don't like the name of the Worksheet/Tab). They are much less likely to change the CodeName of the Worksheet. Some would also say you'd ideally use a Hungarian-style notation too, so you sometimes see each sheet's CodeName changed to sh{LogicalName} or similar.

I expect, since you have run it fine to date, that Sheet2 is indeed the CodeName of your Worksheet with the serial numbers, but that its Name is different...and that is why V4 was replacing the serial numbers.
 
Upvote 0
understood for some reason it wasn't working before when I left both name as "sheet2" I ended up changing both the Codename and the Worksheet name to something very unique like "Locationxdata" and that seemed to do the trick

so lets say I want to protect any other multiple sheets from this macro can I just add multiples line like this into the vba

VBA Code:
               If (ws.Name <> "Location1" And ws.CodeName <> "Sheet2") Then
               If (ws.Name <> "Location2" And ws.CodeName <> "Sheet3") Then
               If (ws.Name <> "Location3" And ws.CodeName <> "Sheet5") Then
please let me know if thats correct at all
 
Upvote 0
That’s one option, provided the subsequent Ifs are ElseIf and there is nothing done in those conditions and the final Else has the replacement code

Though when you get several items to test Select Case is cleaner.

Not tested...something like:

For Each ws In Worksheets
Select Case ws.CodeName
Case "Sheet1", "Sheet2", "Sheet3"
{do nothing}
Case Else
{do the replacement code}
End Select
Next ws
 
Upvote 0
Thank you So much @kennypete I cannot express enough how thankfull I am for you taking the time to help me out figuring all this out. I have a long way to go hopefully someday I can become half as smart as you sir
 
Upvote 0
Thank you So much @kennypete I cannot express enough how thankfull I am for you taking the time to help me out figuring all this out. I have a long way to go hopefully someday I can become half as smart as you sir
You’re welcome @Carlit007, I’m glad you learned along the way. You’ll find many far more adept Excel gurus on this forum than me, though thanks for the kudos. Cheers
 
Upvote 0

Forum statistics

Threads
1,215,059
Messages
6,122,917
Members
449,093
Latest member
dbomb1414

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