Excel: Overwrite column B value when column A value is higher


Question:  I have an Excel spreadsheet that contains a regularly updated list of share prices downloaded from the web in column A. In column B, I want to (automatically) record the highest price each share has reached. So I want column B to increase to the value in column A, but only when column A > column B.


Answer:  This can be done with a macro.


Let's take a look at an example.


Download Excel spreadsheet (as demonstrated below)




In our spreadsheet, the daily quotes are stored in column A and the highest prices are in column B.


We placed a button on the sheet that when clicked will update the values in column B if the corresponding value in column A is higher. When the macro is complete, the following message will appear.




To view the macro, press Alt-F11 and double-click on the module called Module1 in the left window.


You may need to modify the Lrows variable if the macro needs to check more than the first 200 rows in the spreadsheet.


Macro Code:

This macro code looks like this:

Sub UpdateHighestPrices()


    Dim LLoop As Integer


    Dim Lrows As Integer


    Dim LQuote As String
    Dim LHighestVal As String


    'Update first 200 rows in spreadsheet with highest prices
    Lrows = 200


    LLoop = 2


    'Check first 200 rows in spreadsheet
    While LLoop <= Lrows
        LQuote = "A" & CStr(LLoop)
        LHighestVal = "B" & CStr(LLoop)


        'Update value in column b, if value in column B is higher
        If Range(LQuote).Value > Range(LHighestVal).Value Then
            Range(LHighestVal).Value = Range(LQuote).Value
        End If


        LLoop = LLoop + 1
    Wend


    MsgBox "The highest prices have been updated."


End Sub

Spreadsheet News


Book Shop


Visit our busy book shop, were you can find latest books for beginners as well as advanced excel users.



Software Library




Spreadsheet123

Spreadsheet 123 Spreadsheet Software Development

Home | About Us | Our Services | Software | Spreadsheets Library | Excel Tutorials | Useful Links | Site Map | Contact Us
Home
About Us
About Spreadsheet
Book Shop
Excel Tutorials
1
Spreadsheets Library
3
4
5
6
Our Services
8
Site Map
Software
11
12
13
14
15
16
17