Do While loop with dates. Trying to find min and max values for a given year... help!

Axel2

New Member
Joined
Oct 13, 2015
Messages
4
As you can imagine, I just started programming with VBA, and I've decided to tackle a problem with dates... With limited success up to now. I'm using MAC Excel 2011.

I have a table with three columns, the 1st column has dates, the second and third, prices.

For a given year, I'm trying to find the max in the first column, and the min in the second column.

Up to now, here's what I've comed up with:


Code:
Dim vMin As Long, vMax As Long
Dim Journee As Date
Dim enddate As Date


Sub ShowMinMax()

Sheets("Prices").Activate


Journee = CDate(Format("1/1/2015", "mm/dd/yyyy"))
enddate = Now

Do While Journee < enddate
Journee = DateAdd("d", 1, Journee)
vMin = Application.WorksheetFunction.Min(Columns("C"))
vMax = Application.WorksheetFunction.Max(Columns("B"))
MsgBox "Minimum = " & vMin & ", " & "Maximum = " & vMax, vbInformation, "Get Min/Max Values"\
Loop

Next
End Sub

Code:
Here's a sample of my data:

The results wanted are : For 2015 (Max = 92,92; Min = 80,90), For 2014 (Max = 93,28; Min = 83,30), etc...


2015-10-0288,7783,85
2015-07-0389,4182,30
2015-05-0292,9285,18
2015-03-0190,8783,12
2015-01-0488,4280,90
2014-12-0390,2887,22
2014-09-0493,2888,51
2014-06-0390,9984,41
2014-04-0388,4583,30
2014-02-0191,8886,89

<tbody>
</tbody>

















Thanks for your help!
 

Trebor76

Well-known Member
Joined
Jul 23, 2007
Messages
4,467
Hi Axel2,

Welcome to MrExcell!!

Assuming your data is across columns A to C and the data starts at row 2, this will do the job (it does my PC - not sure if it will need tweaking for a Mac):

Code:
Option Explicit
Sub Macro1()

    Dim dteStartDate As Date
    Dim dteEndDate As Date
    Dim lngMyMax As Long
    Dim lngMyMin As Long
    Dim rngMyCell As Range
    
    dteStartDate = CDate("2014-01-01")
    dteEndDate = CDate("2014-12-31")
    
    Application.ScreenUpdating = False
    
    For Each rngMyCell In Range("A2:A" & Range("A:C").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row)
        If CDate(rngMyCell) >= dteStartDate And CDate(rngMyCell) <= dteEndDate Then
            'Set the 'lngMyMax' variable
            If lngMyMax = 0 Then
                lngMyMax = CLng(Range("B" & rngMyCell.Row))
            Else
                If CLng(Range("B" & rngMyCell.Row)) > lngMyMax Then
                    lngMyMax = CLng(Range("B" & rngMyCell.Row))
                End If
            End If
            'Set the 'lngMyMin' variable
            If lngMyMin = 0 Then
                lngMyMin = CLng(Range("C" & rngMyCell.Row))
            Else
                If CLng(Range("C" & rngMyCell.Row)) < lngMyMin Then
                    lngMyMin = CLng(Range("C" & rngMyCell.Row))
                End If
            End If
        End If
    Next rngMyCell
    
    Application.ScreenUpdating = True
    
    MsgBox lngMyMax & vbNewLine & lngMyMin

End Sub
You know you could do this via a formula? Click here as to how.

Regards,

Robert
 

Axel2

New Member
Joined
Oct 13, 2015
Messages
4
Hi Robert,

Thank you so much for this code, it worked great!

I adapted it for the needed years and it's a real gem.

Thanks again,

Axel

Do you have any links or website to learn good vba coding? Thanks
 

Trebor76

Well-known Member
Joined
Jul 23, 2007
Messages
4,467
Hi Axel,

Glad we got it sorted :)

Many of the excel forums just like MrExcel are a great way to learn how to code ;)

Regards,

Robert
 

Michael M

Well-known Member
Joined
Oct 27, 2005
Messages
18,199
Office Version
2013
Platform
Windows
Also, have a look through this list, kindly compiled by Hiker95....there are sites, books, tutorials, etc.
The link to DataPig Technologies has some great video tutorials

What Is VBA?
VBA is an acronym for Visual Basic for Applications. VBA should not be confused with VB, which is standard Visual Basic. Visual Basic for Applications is a programming feature designed by Microsoft for use with their Microsoft Office


MrExcel's Products: Books, CDs, Podcasts

There are over 1800 Excel videos/tutorials here:
ExcelIsFun - YouTube

Getting Started with VBA.
DataPig Technologies

If you are serious about learning VBA try
Macros Made Easy for Microsoft Excel

Excel Tutorials and Tips - VBA - macros - training
Excel Tutorial | Excel Tips | Excel Articles

Free VBA Course
Free VBA Course

Excel 2007 VBA materials to learn here:
VBA for Excel 2007 tutorial-VBA programming?

Here's a good primer on the scope of variables.
Understanding Scope

Using Variables in Excel VBA Macro Code
Excel VBA Variables. Using Variables in Excel VBA Macro Code

See David McRitchie's site if you just started with VBA
Getting Started with Macros and User Defined Functions

What is a VBA Module and How is a VBA Module Used?
What Is A VBA Module and how is a VBA Module Used?

Events And Event Procedures In VBA
Events In Excel VBA

Here is a good introductory tutorial using a VBA Class:
Classes In VBA

There's a chapter on classes in VBA Developer's Handbook which is also good.
VBA Developer's Handbook, 2nd Edition: Ken Getz, Mike Gilbert: 0025211229781: Amazon.com: Books

Ron's Excel Tips
Excel for Windows Tips

Ron de Bruin's Mail from Excel and make/mail PDF files (Windows)
Mail from Excel and make/mail PDF files (Windows)

Anthony's Excel VBA Page - Excel Application - Excel Consultant - Excel Consulting (see 3 tutorials in Excel VBA Basic Tutorial Series)

BET: Microsoft Excel Visual Basic

Debugging VBA
Debug Excel VBA Macro Code
TechBookReport - Debugging Excel VBA Code

Start at the beginning...

Creating An XLA Add-In For Excel, Writing User Defined Functions In VBA
Creating An XLA Add In

Creating custom functions
Creating custom functions - Excel

Writing Your First VBA Function in Excel
Writing Your First VBA Function in Excel | Custom Functions

VBA for Excel (Macros)
Excel Macros (VBA) Tutorial

Excel Macros Tutorial
Excel Macros (VBA) Tutorial

Excel Macros & Programming
EXCEL Macros Tutorial

VBA Lesson 11: VBA Code General Tips and General Vocabulary
VBA for Excel macros language

Excel VBA -- Adding Code to a Workbook
http://www.contextures.com/xlvba01.html

Beyond Excel's recorder

Helpful as a simple concise reference for the basics, and, using the macro recorder is endlessly powerful.
MS Excel: Cells

Learn to debug:
Debugging VBA

How To: Assign a Macro to a Button or Shape
How To: Assign a Macro to a Button or Shape - Peltier Tech Blog

User Form Creation
http://www.contextures.com/xlUserForm01.html

When To Use a UserForm & What to Use a UserForm For
When to use Userform & What To Use Them For. Excel Training VBA 2 lesson 2

Excel Tutorials / Video Tutorials - Functions
http://www.contextures.com/xlFunctions02.html

How to insert Buttons, radio buttons and check boxes in Excel
How to insert Buttons, radio buttons and check boxes in Excel - Bing Videos

INDEX MATCH - Excel Index Function and Excel Match Function
http://www.contextures.com/xlFunctions03.html

Multi or two way vlook up and index match tutorial
Get Digital Help - Excel formulas, array formulas, vba, charts, pivot tables, templates and much more.

Excel Data Validation
http://www.contextures.com/xlDataVal08.html#Larger
http://www.contextures.com/excel-dat...ation-add.html

Excel -- Data Validation -- Create Dependent Lists
http://www.contextures.com/xlDataVal02.html

Your Quick Reference to Microsoft Excel Solutions
XL-CENTRAL.COM : For your Microsoft Excel Solutions

New! Excel Recorded Webinars
DataPig Technologies

Fuzzy Matching - new version plus explanation

Programming The VBA Editor - Created by Chip Pearson at Pearson Software Consulting LLC
This page describes how to write code that modifies or reads other VBA code.
Programming In The VBA Editor

VBA and Macros for Microsoft Excel, by Bill Jelen "Mr.Excel" and Tracy Syrstad

Excel Hacks 100 Industrial-Strength Tips & Tools, by David & Traina Hawley

VBA and Macros for Microsoft Excel 2007, by Bill Jelen "Mr.Excel" and Tracy Syrstad

John Walkenbach's power programming with Excel books.

Excel 2010 Power Programming with VBA, Mr. Spreadsheet's Bookshelf

by Stephen/ Bovey, Rob/ Green, John Bullen (Paperback - Feb 11, 2005)
Professional Excel Development

by Rob Bovey, Stephen Bullen, John Green, and Robert Rosenberg (Paperback - Sep 26, 2001)
Excel 2002 VBA: Programmers Reference

Professional Excel Development by Rob Bovey, Dennis Wallentin, Stephen Bullen, & John Green

DonkeyOte: My Recommended Reading, Volatility
Volatile Excel Functions -Decision Models

A list of Reference Books
AJP Excel Information

Sumproduct
http://www.xldynamic.com/source/xld.SUMPRODUCT.html

Arrays
VBA Array Basics
VBA Arrays
Excel: Introduction to Array Formulas - Xtreme Visual Basic Talk
Excel VBA Chpter 21: Array in Excel VBA

Array Dimensions in Visual Basic - Working with Dimensions (code and graphics)
Array Dimensions in Visual Basic

Shortcut Keys in Excel 2000 through 2007

Pivot Intro
Using Pivot Tables and Pivot Charts in Microsoft Excel
Office 2010 Class #36: Excel PivotTables Pivot Tables 15 examples (Data Analysis) - YouTube
Office 2010 Class #36: Excel PivotTables Pivot Tables 15 examples (Data Analysis) - YouTube
Getting Started with Pivot Tables
http://www.contextures.com/xlPivot01.html#Start
Overview of PivotTable and PivotChart reports
Overview of PivotTable and PivotChart reports - Excel
Build a Pivot Table in Excel VBA
Excel VBA - Build A Pivot Table In Excel VBA Tutorials

Conditional Formatting
Use a formula to apply conditional formatting - Excel

Email from XL - VBA
Mail from Excel example pages

Outlook VBA
Writing VBA code for Microsoft Outlook

Excel Function Dictionary by Peter Noneley
http://www.xlfdic.com/
www.xlfdic.com Excel Function Dictionary 150 example functions and formula.

Function Translations
Excel 2007 function name translations - Dictionary Chart Front Page

Dynamic Named Ranges
http://www.contextures.com/xlNames01.html

How to create Excel Dashboards
http://www.contextures.com/excel-dashboards.html
Excel Dashboards - Templates, Tutorials, Downloads and Examples | Chandoo.org - Learn Microsoft Excel Online
Excel Dashboards - Templates, Tutorials, Downloads and Examples | Chandoo.org - Learn Microsoft Excel Online
Free Microsoft Excel Dashboard Widgets to Download
AJP Excel Information - Gauge

Excel Dashboard / Scorecard Ebook
Excel Dashboards and Scorecards Ebook | How to Create Dashboards in Excel

Mike Alexander from Data Pig Technologies
Amazon.com: Excel 2007 Dashboards and Reports For Dummies (9780470228142): Michael Alexander: Books

Templates
CPearson.com Topic Index
http://www.contextures.com/excel-tem...lf-scores.html
Free Microsoft Excel Template Links & Search Engine

Microsoft Excel Cascading Listboxes Tutorial
Microsoft Excel Cascading Listboxes Tutorial - YouTube

Date & Time stamping:
McGimpsey & Associates : Excel : Time and date stamps

Get Formula / Formats thru custom functions:
Show FORMULA or FORMAT of another cell

A nice informative MS article "Improving Performance in Excel 2007"
Improving Performance in Excel 2007

Progress Meters
AJP Excel Information - Progress meters
xcelfiles.com

How to convert text to numbers in Excel
How to convert text to numbers in Excel

How to parse data from the web - Brett Fret has a video in YouTube
Excel VBA - Easily parse XML data from a file or website using XML Maps - YouTube

Excel VBA MAC shortcuts
Mac Shortcuts for Excel

Macintosh Keyboard Shortcuts to use in Microsoft Excel
Excel keyboard shortcuts - mac excel

Excel shortcut and function keys - Excel

And, as your skills increase, try answering threads on sites like:
MrExcel.com | Excel Resources | Excel Seminars | Excel Products
Excel Help Forum
Excel Templates | Excel Add-ins and Excel Help with formulas and VBA Macros
Expert Microsoft Help, with all of the Microsoft Applications from Excel programming, Access training to our free Microsoft VBA Forums
Excel, Access, PowerPoint and Word VBA Macro Automation Help

If you are willing to spend money for the training, then something here should work for you...
Amazon.com: excel tutorial dvd

Advanced Excel Training - Online Excel Course
http://www.udemy.com/advanced-excel/
 

Forum statistics

Threads
1,082,305
Messages
5,364,406
Members
400,801
Latest member
julievandermeulen

Some videos you may like

This Week's Hot Topics

  • populate from drop list with multiple tables
    Hi All, i have a drop list that displays data, what i want is when i select one of those from the list to populate text from different tables on...
  • Find list of words from sheet2 in sheet1 before a comma and extract text vba
    Hi Friends, Trying to find the solution on my task. But did not find suitable one to the need. Here is my query and sample file with details...
  • Dynamic Formula entry - VBA code sought
    Hello, really hope one of you experts can help with this - i've spent hours on this and getting no-where. .I have a set of data (more rows than...
  • Listbox Header
    Have a named range called "AccidentsHeader" Within my code I have: [CODE]Private Sub CommandButton1_Click() ListBox1.RowSource =...
  • Complex Heat Map using conditional formatting
    Good day excel world. I have a concern. Below link have a list of countries that carries each country unique data. [URL...
  • Conditional formatting
    Hi good morning, hope you can help me please, I have cells P4:P54 and if this cell is equal to 1 then i want row O to say "Fully Utilised" and to...
Top