Excel Vba Examples

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 133
At a glance
Powered by AI
The document describes various macros for rearranging and manipulating data in Excel.

Join(), JoinRows(), Lastname(), Firstname(), and others are described for rearranging columns and rows of data.

MarkCells(), FillSequence(), and MarkSepAreas() are described for generating test data.

Rearranging Data in Columns

Location: http://www.mvps.org/dmcritchie/excel/join.htm Home page: http://www.mvps.org/dmcritchie/excel/excel.htm [View without Frames] This page contains some VBA macros. If you need assistance to install or to use a macro please refer to Getting Started with Macros. For more depth see Install a Macro or User Defined Function on my Formula page.
Speed and efficiency considerations can be seen in Proper, and other Text changes and in Slow Response.

Many of the macros here are useful for reformatting name and address listings, and others for creating test data. This document describes macros for Join() Joins selected columns on a row by row basis and includes a space between each cell concatenated. Reverse of SepTerm(). JoinRows() Joins Rows within a column within a single area selection. Vertical equivalent of JOIN(). Lastname() Put lastname before firstname, unless cell in the range already has a comma. Firstname() Put firstname before lastname, for cells with "Lastname, Firstnames". FixUSzip5() and FixCANADAzips Fixup for 5 digit zip codes that have been stripped of first zero or show as a number. FixCANDAzips restores missing space in Canadian zip codes. Firstname() Put firstname before lastname, for cells with "Lastname, Firstnames". Fix_PhoneAreaCode() Fixup to add default area code to 7 digit local area code phone numbers. Debug Format Use of Worksheet Functions to determine the actual data content: ISNUMBER, ISTEXT, LEN, ISBLANK, CODE, GetFormula, GetFormat ReEnter() Reenter the content in a cell. Generally to activate things you have changed the underlying formats. Also see TrimALL() to TRIM all cells in a selection, followed by RemoveAllSpaces to remove all spaces and char(160). ReEnterSuff_F() Append a suffix to a value or formula to make a formula RemoveAllSpaces Remove all spaces and Char(160). variation: RemoveAllSpaces2() leaves row 1 intact. ReversI() Reverses the items in a selection so that the first becomes the last, and the last becomes the first. RotateCW() Rotate Selected area A1:xxx clockwise SepTerm() Separate first word (term) from remainder. Remainder goes to next column. Reverse of Join. much more restrictive than Data --> Text to Columns.

Sep3Terms() Separate lastname, firstnames into 3 entities: Firstname | Middlenames | Lastname. SepLastTerm() Separate last word and place into next column. Remainder remains in current column. Reverse of Join. much more restrictive than Data --> Text to Columns. Concept is similar to SepTerm(). Also available on the code\join.txt page are SepLastName for people's names, SepLastWord uses StrReverse new in Excel 2000, LastWord function uses StrReverse, resubstr function using VBA Script. TrimALL() Trims all cells in a selection The above macros do not actually destroy data, and can be reversed out (subject to some restrictions). Some additional worksheet function and macro usage Rearrangements based on comma Replace strings in a macro (ReplaceCRLF) Use of REPT worksheet function, REPT repeats text a given number of times. The following macro can be used to generate TEST data. MarkCells() Creates test data by placing the cells address as the value for each cell in the selected range. Samples for this page. i.e. A1,B1,C1,A2,B2,C2,C1,C2,C3. FillSequence() Creates test data by sequential numbers into selected range(s). i.e. 1,2,3,4,5,6,7,8,etc. MarkSepAreas() Creates text data across multiple ranges (areas) to create test data containing text value of cell address followed by the area number for each cell in the selected ranges. i.e. A1-1, B1-1, B22,C2-2,D2-2 Related macros on other pages of mine (also see Related Fill Empty includes manual steps, and macro solutions to fill in empty cells below descriptive headers, so a table column can be sorted. Some additional topics on this page, some are brief descriptions pointing to another page DebugFormat Some tips for determining what kind of data you actually have in a cell, is it a number or is it text, and why is it seen that way. ReproduceActive Reproduce Formula in ActiveCell to selected ranges(s) Simple multiplication and addition table examples. Fill handle used to fill cells by dragging current selection by the fill handle. shortcut keys Creating a sheet to document the builtin Excel shortcut keys. (also how to add your own).

General Comments

Have tried to limit the scope of Join() and SepTerm() by checking for the lastcell. Without some kind of a limitation the macro subroutines would take a very long time cycling through 16384 rows in XL95, or 65536 rows in XL97 and later. The limitation can be corrected better (come back in a year). All of the macros can work with a selection involving multiple rows and columns. In SepTerm selection of a single or multiple columns is the same. The cells to the right of the first column will be verified as empty or containing only spaces.

Join Cells (reversal of Text to columns)


[Ctrl+j] Sub Join() 'David McRitchie 1998-08-05 [Ctrl+j] documented in ' http://www.mvps.org/dmcritchie/excel/join.htm 'Join cells in selected portion of a row together 'can be used as a reversal of Data/Test2cols or SepTerm() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual On Error Resume Next Dim iRows as Long, mRow as Long, ir as Long, ic as Long iRows = Selection.Rows.Count Set lastcell = cells.SpecialCells(xlLastCell) mRow = lastcell.Row If mRow < iRows Then iRows = mRow 'not best but better than nothing iCols = Selection.Columns.Count For ir = 1 To iRows newcell = Trim(Selection.Item(ir, 1).Value) For ic = 2 To iCols trimmed = Trim(Selection.Item(ir, ic).Value) If Len(trimmed) <> 0 Then newcell = newcell & " " & trimmed Selection.Item(ir, ic) = "" Next ic Selection.Item(ir, 1).Value = newcell Next ir Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

(#join)

Join() can be used as a reversal of Text to Columns, and to reverse SepTerm() described later. A range must be selected. See Samples below for an example of usage. Suggested shortcut key

JOINROWS, join content of cells vertically within selection (#joinrows)


Code not shown is included with code for other macros described on this page. See Samples below for an example of usage.

Lastname formatting

(#lastname)

Lastname() can be used to rearrange cells so that lastname appears first in cells in selected range. The range is for one column only. If there is a comma in a cell, the cell will be left alone; otherwise, the cell will be recomposed with the word after the last space first followed by a comma, and the first names. See Samples below for an example of usage.

Sub Lastname() 'David McRitchie 1999-04-09 ' http://www.mvps.org/dmcritchie/excel/join.htm 'Put cells in range in as Lastname, firstnames '--Application.ScreenUpdating = False 'On Error Resume Next iRows = Selection.Rows.Count Set lastcell = cells.SpecialCells(xlLastCell) mrow = lastcell.Row If iRows > mrow Then iRows = mrow imax = -1 For ir = 1 To iRows checkx = Trim(Selection.item(ir, 1)) L = Len(Trim(Selection.item(ir, 1))) If L < 3 Then GoTo nextrow For im = 2 To L If Mid(checkx, im, 1) = "," Then GoTo nextrow If Mid(checkx, im, 1) = " " Then imax = im Next im If imax > 0 Then Selection.item(ir, 1) = Trim(Mid(checkx, _ imax, L - imax + 1)) & ", " & _ Trim(Left(checkx, imax)) End If nextrow: Next ir terminated: '--Application.ScreenUpdating = True End Sub

Firstname before Lastname formatting (#firstname)


Switch selected cells from "lastname, firstnames" to "firstnames lastnames" based on having a comma in position 2 or higher. This code is shorter and more efficient than the lastname macro because it was written later. See Samples below for an example of usage.
Sub FirstName() 'David McRitchie 2000-03-23 programming 'http://www.mvps.org/dmcritchie/excel/join.htm#firstname Application.ScreenUpdating = False Application.Calculation = xlManual Dim cell As Range Dim cPos As Long For Each cell In Selection.SpecialCells(xlConstants, xlTextValues) cPos = InStr(1, cell, ",") If cPos > 1 Then origcell = cell.Value cell.Value = Trim(Mid(cell, cPos + 1)) & " " _

& Trim(Left(cell, cPos - 1)) End If Next cell Application.Calculation = xlAutomatic 'xlCalculationAutomatic Application.ScreenUpdating = False End Sub

Worksheet formulas
A worksheet function solution maintaining two columns, one with the original data and one with the rearrangement. You could, of course, eliminate the dependence with copy, the Edit, paste special, values and then eliminate the original column. This converts "lastname, firstname" to "firstname, lastname" =TRIM(MID(B7,FIND(",",B7)+1,99))&" "&LEFT(B7,FIND(",",B7)-1)

Fix up for 5 digit US zip codes

(#fixUSzip5)

US zipcodes are 5 digit or 9 digit (01234-1234) called zip+4. Only the 5 digit zipcodes are a problem because they get interpreted as a number and get leading zeros stripped. The fixUSzip5 subroutine will repair the damage generally introduced by the Text to Data wizard or by software converting a scanned image to an Excel file. Canadian zip codes are unaffected because they are not numeric. US zipcodes do not begin with two zeros, but a medication has been made for someone using 3 digit numbers for other countries and the Caribbean. After running macro suggest formatting the column as TEXT and remove any cell alignment. Some worksheet formulas to help show what you actually have: =IF(ISTEXT(E2),"T",IF(ISNUMBER(E2),"N","L"))&LEN(E2) =personal.xls!GetFormat(E2) See the code for a macro (fixCANADAzips) to fix Canadian zip codes codes where the required space was omitted.
Sub FixUSzip5() 'David McRitchie 2000-04-28 notposted, updated 2001-12-14 'http://www.mvps.org/dmcritchie/excel/join.htm#fixUSzip5 Application.ScreenUpdating = False Application.Calculation = xlManual Dim cell As Range Dim cValue Dim cPos As Integer Selection.Replace What:=Chr(160), Replacement:=Chr(32), _ LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False 'Trim in Excel removes extra internal spaces, VBA does not On Error Resume Next For Each cell In Selection.SpecialCells(xlConstants, 2) 'trim text cells cell.Value = Application.Trim(cell.Value) Next cell For Each cell In Selection.SpecialCells(xlCellTypeConstants, 1) 'special modification to also use 3 digits as if valid If Len(cell) = 4 Or Len(cell) = 5 Or Len(cell) = 3 Then cValue = cell.Value cell.NumberFormat = "@"

cell.Value = Right("00000" & CStr(cell.Value), 5) End If Next cell Application.Calculation = xlAutomatic 'xlCalculationAutomatic Application.ScreenUpdating = False End Sub

Worksheet solutions for US zip codes


Formatting numbers in zip code format: (Format, Cells, custom), will still be numbers and text (suggest left justifying) [<100000]00000_-_0_0_0_0;[>0]00000-0000;;@ Make everything text for 5-digit and zip+4 all will be text (sortable as text ) =TEXT(F2,"[<100000]00000_-_0_0_0_0;[>0]00000-0000;;@") Make everything 5 character zip codes with leading zeros - strip last 4 digits of 9-digit zip codes (sortable as text) =LEFT(TEXT(F2,"[<100000]00000;[>0]00000-0000;;@"),5) The underscores are reserving space on the right equivalent to a numeric digit. All numeric digits in the same font have the same width by design. (see my formula page).

First 3 digits of zip codes, Worksheet Solution


Sorting on the first 3 digits may be the minimum requirement for a particular class of mail. Your zipcodes should be text but if they are numbers then you will have a problem taking the left 3 digits, in which case something like the following will take care of mixed zipcodes as 5digit text, zip+4 text, or 5 digit numbers. The result will be 3 digit text entries. This is a Worksheet solution.
=IF(TRIM(A1)="","",IF(ISTEXT(A1),LEFT(A1,3),TEXT(INT(A1/100),"000")))

First group of characters for Canadian or UK zip codes


=IF(ISERR(FIND(" ",A1)),A1,LEFT(A1,FIND(" ",A1)-1))

Fix Local Area Phone Codes

(#fixphoneareacode)

As US phone area code apply to smaller and smaller areas, and even moving into overlapping Area Codes, fixing up phone lists to include area code is becoming a very frequent event. The following will convert phone numbers such as 555-1212 as text or formatted number to text (xxx) 555-1212.
Sub Fix_PhoneAreaCode() Dim cell As Range On Error Resume Next 'in case nothing found Dim AreaCode As String

AreaCode = "412" AreaCode = InputBox("Supply your local area code " & _ "to be prefixed to phone numbers without an area code" _ & Chr(10) & " i.e. " & AreaCode _ & " will prefix current entries with ""(" & _ AreaCode & ") """, "Supply Area Code", AreaCode) If AreaCode = "" Then Exit Sub AreaCode = "(" & AreaCode & ") " For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlConstants, xlTextValues)) If Len(cell) = 8 Then 'as in 555-1212 cell.Value = AreaCode & Trim(cell.Value) End If Next cell 'On Error Resume Next -- continues in effect For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlConstants, xlNumbers)) If cell > 999999 And cell < 9999999 Then cell.Value = AreaCode & Format(cell.Value, "000-0000") End If Next cell End Sub

Reverse Cells in Selection end for end

(#reversi)

ReversI() can be used to reverse the order of items in a row, column, or range. It can be used to reverse itself. Applied to a SINGLE ROW, the macro will flip about a vertical axis, or a horizontal axis for a column; otherwise, it really isn't a flip. Obviously you must select the range (i.e. A1:A30) and not the entire row or column. If you selected an entire row for instance your data would be so far to the right that it would take you awhile to find it. If you select a range of columns and rows the item in the upper left will reappear in the lower right corner. What previously was ordered down will be up, and what ran left to right will run right to left. You may notice the division by two; if the item count is not divisible by two the center item will not be switched. Infrequent use does not justify a shortcut key. See Samples below for an example of usage. Sub ReversI() 'David McRitchie 1998-07-30 documented in ' http://www.mvps.org/dmcritchie/excel/join.htm 'Reverse (Flip) Item values in Range, Row, or Column [Ctrl+R] 'Counting in multiple rows/cols, item count proceeds down a 'column in range and continues top of next column in range Dim tcells As Long, mCells As Long, ix As Long, ox As Long Dim iValue As Variant tcells = Selection.Count mCells = tcells / 2 For ix = 1 To mCells iValue = Selection.Item(ix).Value ox = tcells + 1 - ix Selection.Item(ix).Value = Selection.Item(ox).Value Selection.Item(ox).Value = iValue

Next ix End Sub

Rotate Selection Clockwise

(#rotatecw)

This Subroutine will Rotate the selection area A1:xnn 90 degrees ClockWise. Because Rows are copy and pasted and because TRANSPOSE is used in this macro all formatting, and formulas are preserved. See RotateCW() Sample in the Sample area. Part 1, Rotate the Rows Part 2, TRANSPOSE the rotated Rows for selection area -- Full rows Note: As written the selection area must include cell A1, and the original selection area is really the entire rows. This is practical as long as there are not more than 256 rows selected because of the longstanding 256 column limitation in Excel. This macro was written to normalize a spreadsheet that could best be views sideways and had rotated cells that became available in XL97. Until rewritten arrangement or presence of cells not in selection is undefined.
Sub RotateCW() 'Rotate Clockwise: 1) Rotate rows, 2) TRANSPOSE & delete orig 'David McRitchie, 2000-02-07 MISC., documented in ' http://www.mvps.org/dmcritchie/excel/join.htm 'Cell A1 must be in Selection !!!!! 'must formatting and Formulas are preserved Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim i As Integer Dim nRows As Integer Dim nCols As Integer Dim curRange As Range Dim abc As String Set curRange = Selection nRows = Selection.Rows.Count nCols = Selection.Columns.Count If nRows > 256 Then GoTo done nRows = InputBox("Specify number of rows, suggesting " & nRows, _ "Selection of Number of rows to Rotate", Selection.Rows.Count) nRows = nRows + 1 'adjustment for inserts For i = nRows To 2 Step -1 Rows(1).Select Selection.Cut Rows(i).Select Selection.Insert Shift:=xlUp Next i 'Have flipped the rows, next step is to TRANSPOSE data with copy abc = "1:" & nRows - 1 Range(abc).Select i = MsgBox("Flipping of Rows Completed. Do you want to continue " & _ "with a TRANSPOSE using COPY?", vbOKCancel, "Question") If i <> 1 Then GoTo done Selection.Copy

Cells(nRows, 1).Select 'TRANSPOSE to Selection.PasteSpecial Paste:=xlAll, Operation:=xlNone, SkipBlanks:=False _ , Transpose:=True Range(Cells(1, 1), Cells(nRows - 1, 256)).Delete done: Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub

Separate first word (term) from remainder of cell (#septerm)


SepTerm() separates the first word (term) from remainder of cell. Remainder goes to next column. SepTerm() can be used as a reversal of Join and is a more forgiving option than Data --> Text to Columns. SepTerm() Can be used to separate the street number from the rest of the street name. Can also be used to separate a term from a definition. Only a single column need to be selected. The next column will be tested that it contains a blank. A check will be made that no cells contain data in the adjacent column to the right, but you can override this. Even after overriding data will not be split if it will remove content from the adjacent column. See Samples below for an example of usage. Suggested shortcut key [Ctrl+t] Sub SepTerm() 'David McRitchie 1998-08-05 [Ctrl+t] documented in ' http://www.mvps.org/dmcritchie/excel/join.htm 'Separate the first term from remainder, as in separating 'street number as first item from street & remainder 'Work on first column, cell to right must appear to be blank '--Application.ScreenUpdating = False 'On Error Resume Next iRows = Selection.Rows.Count Set lastcell = cells.SpecialCells(xlLastCell) mRow = lastcell.Row If mRow < iRows Then iRows = mRow 'not best but better than nothing For ir = 1 To iRows If Len(Trim(Selection.Item(ir, 1).Offset(0, 1))) <> 0 Then iAnswer = MsgBox("Found non-blank in adjacent column -- " _ & Selection.Item(ir, 1).Offset(0, 1) & " -- in " & _ Selection.Item(ir, 1).Offset(0, 1).AddressLocal(0, 0) & _ Chr(10) & "Press OK to process those than can be split", _ vbOKCancel) If iAnswer = vbOK Then GoTo DoAnyWay GoTo terminated End If Next ir DoAnyWay: For ir = 1 To iRows

If Len(Trim(Selection.Item(ir, 1).Offset(0, 1))) <> 0 Then GoTo nextrow checkx = Trim(Selection.Item(ir, 1)) L = Len(Trim(Selection.Item(ir, 1))) If L < 3 Then GoTo nextrow For im = 2 To L If Mid(checkx, im, 1) = " " Then Selection.Item(ir, 1) = Left(checkx, im - 1) Selection.Item(ir, 1).Offset(0, 1) = Trim(Mid(checkx, im + 1)) GoTo nextrow End If Next im nextrow: Next ir terminated: '--Application.ScreenUpdating = True End Sub Considerations in working with data from HTML sources The macro above does not include replacing a non breaking space character (&nbsp;) typically used in HTML, with a normal space. You can achieve the replacement with Worksheet Ctrl+H, Replace: Alt+0160, With: (space) with macro code. Selection.Replace What:=CHR(160), Replacement:=CHR(32), LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False A worksheet solution for the above. This will leave the original column and the two new columns wns will be dependent on the original. You can remove the dependency by using copy and paste special value. That's why I use a macro.
=LEFT(A3,FIND(" ",A3)-1) =MID(A3,FIND(" ",A3)+1,LEN(A3)-FIND(" ",A3))

or if only interested in the street, to remove the number at the beginning, if present, before the first space, use. [Rag Dyer 2005-04-23]
=IF(ISERR(--LEFT(A1,FIND(" ",A1))),"",LEFT(A1,FIND(" ",A1)-1)) -- number if present =IF(ISERR(--LEFT(A1,FIND(" ",A1))),A1,MID(A1,FIND(" ",A1)+1,100)) -- street name

or to include considerations for char(160) but not errors (Peo Sjoblom, misc, 2002-02-17) -- No consideration for errors is all the more reason to use macros.
for street numbers (leftmost word): =LEFT(TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," "))),SEARCH(" ",TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," "))))-1) for street names (remainder): =RIGHT(TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," "))),LEN(TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160), " "))))-SEARCH(" ",TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))))

VBA for Text to Columns Macros on this page were written to reduce or eliminate the exposure of overwriting that would occur with the following Text to Columns.
Selection.TextToColumns Space:=True, ConsecutiveDelimiter:=True

Determine if cell is Number or Text and why is it seen that way (#debugformat)
Finding out what you actually have -- it may not be what it looks like (#debugformat) Formatting: Check what the cell was formatted for with Format, cells and look at the format. Changing the format between Text and Number will have no effect on data already entered, but reentry of data will be changed if valid. Changing the number format for a cell that is a number, shows true for =ISNUMBER(C2), will be immediately effective when the format is changed. Finding out how Excel is recognizing your data is the first step, you can use worksheet functions individually, but you might want to check a lot of cells at one time. Start with selecting a group of cells such as columns D:F to find out if they are blank, numbers, or text. Only cells within the used range will be identified. Each of the following will change your selection so you will have to start over from: Select cells, Ctrl+G (Edit, GoTo), [Special] button {and then use one of the following: to find blanks (empty cells), [x] blanks to find text cells, [x] constants, [x] text to find numbers cells, [x] constants, [x] numbers Some worksheet formulas to help show what you actually have:
=IF(ISTEXT(E2),"T",IF(ISNUMBER(E2),"N","L"))&LEN(E2) =ISNUMBER(E2) =ISTEXT(E2) =LEN(E2) =ISBLANK(E2) [in VBA the equivalent is ISEMPTY] =CODE(E2) =CODE(RIGHT(E2,1)) =personal.xls!GetFormula(E2) =personal.xls!GetFormat(E2) ="'*" & D6 & "*" & CODE(RIGHT(D6,1))

Cell View, http://www.cpearson.com/excel/CellView.htm, Chip Pearson, addin shows the Ascii Code for each character in a cell, which be easier than invoking CODE Worksheet Function for each character yourself (ASC in VBA). The most common problems would be finding 010 for line-break and not having cell-wrap format option turned on, finding 013 for Carriage-Return which is ignored in Excel, or finding 160 for the non-breaking space

character (&nbsp;) introduced by pasting HTML into Excel (see TrimALL macro below. The CODE Worksheet Function determines the ASCII code for a single character. The TRIM Worksheet Function will remove code 32 space from left and right sides. But a macro such as TRIMALL can simply the TRIM by doing it in place and by converting the HTML &nbsp; (non-breaking space) character 160 to spaces before trimming. The formula or text may be reentered by hitting F2 (activate cell and formula bar) then Enter, which is fine for individual cells. Another manual technique is the Replace (Ctrl+H) all equal signs (=) by equal signs. Hitting F9 (Recalculate) will cause a reevaluation based on what is left, if done from the formula bar with highlighted text. J K Formula in Add Formula in SUM 6 Text Number Add Sum Column Column 7 1 2 3 2=F7+G7 =SUM(F7,G7) 8 2 2 4 2=F8+G8 =SUM(F8,G8) 9 3 2 5 5=F9+G9 =SUM(F9,G9) 10 4 2 6 2=F10+G10 =SUM(F10,G10) 11 XX 2#VALUE! 2=F11+G11 =SUM(F11:G11) 12 XX xx #VALUE! 0=F12+G12 =SUM(F12:G12) F G H I L M ISNUMBER for ISNUMBER for Column F col G FALSE TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE FALSE

Cell F9 is formatted as a number before entry; the rest in the column are formatted as text before entry.

Reenter the cell current cell content (#reenter)


When you change the format between text and numbers (could be either under General) the actual format does not change until the content is reentered. Changes between numeric formats are immediate. You can check how Excel sees the data with =ISTEXT(A1) -- see debugformat. You could have some non-breaking spaces in a formula -- see TrimALL macro. Reenter using Worksheet solutions after changing the format, one of the following should work. F2 then Enter (even though this is one at a time this is good to see if this is the problem) Change "=" to "=" using Ctrl+H (good to activate formulas, also make sure Calulation is set to Automatic) Select an empty cell, copy with Ctrl+C, select the cells to be reentered such as a column, Edit, Paste Special, Add use a macro such as one of the following:

ReEnter() renters the content of cell. Useful for such things as dates coming in from csv file that were not accepted as dates but have date content. if using F2 and Enter will speed up the process this will be faster. Also see my datetime page.
Sub ReEnter() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim cell As Range Dim ix as Long tCells = Selection.Count For ix = 1 To tCells Selection.Item(ix).Formula = Trim(Selection.Item(ix).Formula) Next ix Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub

Apparently need to use F2 to reenter an email address so back to an updated version that really doesn't make any difference whether screen updating is turned off or not.
Sub ReEnterF2() ' successfully will reenter email addresses Dim cell As Range, rng As Range, rng2 Dim tcells As Long, ix As Long Set rng = Intersect(Selection, ActiveSheet.UsedRange) Set rng2 = Selection If rng Is Nothing Then Exit Sub Application.ScreenUpdating = False Application.Calculation = xlCalculationAutomatic tcells = rng.Count For ix = 1 To tcells rng.Item(ix).Formula = Trim(rng.Item(ix).Formula) rng.Item(ix).Activate SendKeys "{F2} {enter}" Next ix rng2.Select Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

and the opposite, to make formulas into text. Also see GetFormula() on my Formula page. Tested for single and multiple cell selections with/without formulas Tested for single and multiple cell selections in a sheet without any formulas Following a posting by Ron de Bruin it appears I could have done this without a loop so I will show that version first.
Sub ReEnterAsValues() 'D.McRitchie 2002-12-04 Misc. -- no loops, preferred solution Dim Rng As Range On Error GoTo done Set Rng = Intersect(Selection, Selection.SpecialCells(xlFormulas)) If Rng Is Nothing Then Exit Sub On Error GoTo 0 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim cell As Range

Intersect(Selection, Selection.SpecialCells(xlFormulas)).Value = _ Intersect(Selection, Selection.SpecialCells(xlFormulas)).Value Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True done: End Sub Sub ReEnterAsValues() 'D.McRitchie 2002-12-04 Misc. Dim Rng As Range On Error GoTo done Set Rng = Intersect(Selection, Selection.SpecialCells(xlFormulas)) If Rng Is Nothing Then Exit Sub On Error GoTo 0 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim cell As Range For Each cell In Rng cell.Value = cell.Value 'to get text values instead use ="'" & cell.value Next cell Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True done: End Sub

To convert formula values to value constants. Also see GetFormula() on my Formula page.
Sub ReEnterF2V() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim cell As Range For Each cell In Selection.SpecialCells(xlFormulas) cell.Value = "'" & cell.value Next cell Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub

TrimALL macro

(#trimall)

The following will Trim all constants in the selection. The use of SpecialCells prevents truly empty [ISEMPTY in VBA or ISBLANK in Excel] cells from being processed. CHR(160) is the non breaking space character (&nbsp;) in HTML which will be included by changing them first to normal spaces. There is a difference between TRIM in Excel and in VBA. Excel will reduce internal spaces, VBA will not. Use Trim(Cell.value) if you prefer the VBA method. Other characters you may see are TAB, CR, LF which have decimal values of 09, 13, and 10. The use of the CLEAN Worksheet Function to remove unprintable characters will only remove CHAR(0) through CHAR(31), Char(129), Char(141), Char(143), and Char(144). It will have no effect on Char(160). The use of CLEAN removes the character, you might very well have preferred a space or other character. If you are not getting the results you want reread an earlier topic: Finding out what you actually have -- it may not be what it looks like.

This macro will remove excess spaces, but be sure that is what you want. Removing and converting characters may make record unsuitable to a database that is used to having certain characters as filler. You can check an individual cell with =LEN(C2) and =CODE(LEFT(C2)) and =CODE(MID(C2,LEN(C2),1)) if you experience some problems in your data. Instructions to install and use a macro at the top of this page actually refer you to another page Gettting started with macros.
Sub TrimALL() 'David McRitchie 2000-07-03 mod 2000-08-16 join.htm Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range 'Also Treat CHR 0160, as a space (CHR 032) Selection.Replace What:=Chr(160), Replacement:=Chr(32), _ LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False 'Trim in Excel removes extra internal spaces, VBA does not On Error Resume Next 'in case no text cells in selection For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlConstants, xlTextValues)) cell.Value = Application.Trim(cell.Value) Next cell On Error GoTo 0 Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Most of the need for the TRIMALL macro arises from copying and pasting from an HTML web page. Another problem run into from copy and pasting HTML material is unwanted shapes (pictures, buttons, icons) that were copied along with the text. See shapes.htm for page concerning shapes including macros for deleting all shapes (delShapesOnSht), and selectively deleting shapes (delShapesSel) from a worksheet. The following uses code and suggestions from Dave Peterson I believe is almost equivalent in results to the above and runs in about 1/2 the time as the above for selections involving a large number of cells to actually be changed. There is one difference the above is shown with the Excel TRIM, if it used the VBA TRIM they would be closer. Wouldn't make much difference to me except when CHAR(160) is next to a space, I would want to make sure I end up with only a single space. For that reason I probably will continue to prefer the version above. Though if one had sentences it wouldn't be good to eliminate the extra space after periods. Neither version will affect formulas. It always comes down to knowing your data and your tools and exactly what you want.
Sub TRIMALL_alternate() 'Dave Peterson, programming, 2002-08-17 'http://google.com/[email protected] Dim myRange As Range Dim myCol As Range Set myRange = Intersect(ActiveSheet.UsedRange, Selection) If myRange Is Nothing Then Exit Sub

Application.ScreenUpdating = False myRange.Replace What:=Chr(160), Replacement:=Chr(32), _ LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False For Each myCol In myRange.Columns If Application.CountA(myCol) > 0 Then myCol.TextToColumns Destination:=myCol(1), _ DataType:=xlFixedWidth, FieldInfo:=Array(0, 1) End If Next myCol Application.ScreenUpdating = True End Sub

The following code will Remove all Spaces from the selected area. Compare to TrimAll immediately above. Sub RemoveAllSpaces() 'David McRitchie 2000-10-24 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Selection.SpecialCells(xlConstants).Replace What:=Chr(160), _ Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=True Selection.SpecialCells(xlConstants).Replace What:=Chr(32), _ Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=True Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub Variation to leave row 1 intact
Sub RemoveAllSpaces2() 'David McRitchie 2002-08-27 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Selection.SpecialCells(xlConstants).Replace What:=Chr(160), _ Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=True Selection.SpecialCells(xlConstants).Replace What:=Chr(32), _ Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=True Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Code to convert Text dates in a column to Dates can be found on DateTime page The ASAP Utilities [Download ASAP Utilities], includes over 300 utilities including the option to trim spaces. You can use Chip Pearson's Cell View to view the characters and their corresponding decimal or hexidecimal codes. This should be sufficient for

most usage but Uuencode values not in your font will show with a dec code of 063 or a hex code of 3F.

Append suffix to value or formula (#ReEnterSUFF_F)


The ReEnterSuff_F macro will generate formulas, regardless of whether you started with formulas or not. Default suffix will be taken from cell c1, which you can override. Original content will be enclosed in parentheses if the suffix begins with a left paren. Errors will be ignored. - to ignore range if no formulas in entire range - to ignore range if no constants in entire range - to ignore anything that would result in an incorrect formula
Sub ReEnterSUFF_F() Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic 'David McRitchie 2000-06-24 misc, join.htm in www.mvps.org/dmcritchie/excel/ ' Formulas will result Dim cell As Range Dim mySuff As String Dim myPref As String mySuff = InputBox("Provide suffix i.e. *(1+$b$1) or )*(1+$B$1)", _ "ReEnterSuff: Supply formula suffix", [c1]) If mySuff = "" Then GoTo done If Left(mySuff, 1) = ")" Then myPref = "(" Else myPref = "" End If On Error Resume Next For Each cell In Selection.SpecialCells(xlFormulas) cell.Formula = "=" & myPref & Mid(cell.Formula, 2) & mySuff Next cell For Each cell In Selection.SpecialCells(xlConstants) cell.Formula = "=" & myPref & cell.Formula & mySuff Next cell done: Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Separate Last word (term) from remainder of cell (#seplastterm)


SepLastTerm() separates the last word (term) from remainder of cell. Last word goes to next column, first portion replaces current cell. SepLastTerm() can be used as a partial reversal of Join and is a more forgiving option than Data --> Text to Columns. SepLastTerm() Can be used to separate the first names from the lastname. Another frequent use would be to separate the zip or zip+4 code from a column containing City, State and zipcode. Because zip codes can be 5

digits only and can begin with a zero you should format the column to the right as TEXT before invoking the SepLastTerm macro. Only a single column need to be selected. The next column will be tested that it contains a blank. A check will be made that no cells contain data in the adjacent column to the right, but you can override this. Even after overriding data will not be split if it will remove content from the adjacent column. See specific notes for data preparation immediately after the macro code below. See Samples below for an example of usage. See Considerations for HTML non-breaking-space (&nbsp;) Suggested shortcut key [Ctrl+t] Sub SepLastTerm() 'David McRitchie 1998-08-20 [Ctrl+l] documented in ' http://www.mvps.org/dmcritchie/excel/join.htm 'Separate the last term from remainder, as in separating 'lastname from firstname 'Work on first column, cell to right must appear to be blank Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlAutomatic 'On Error Resume Next Dim iRows as Long, mRow as Long, ir as Long iRows = Selection.Rows.Count Set lastcell = cells.SpecialCells(xlLastCell) mRow = lastcell.Row If mRow < iRows Then iRows = mRow 'not best but better than nothing For ir = 1 To iRows If Len(Trim(Selection.item(ir, 1).Offset(0, 1))) <> 0 Then iAnswer = MsgBox("Found non-blank in adjacent column -- " _ & Selection.item(ir, 1).Offset(0, 1) & " -- in " & _ Selection.item(ir, 1).Offset(0, 1).AddressLocal(0, 0) & _ Chr(10) & "Press OK to process those than can be split", _ vbOKCancel) If iAnswer = vbOK Then GoTo DoAnyWay GoTo terminated End If Next ir DoAnyWay: For ir = 1 To iRows If Len(Trim(Selection.item(ir, 1).Offset(0, 1))) <> 0 _ Then GoTo nextrow checkx = Trim(Selection.item(ir, 1)) L = Len(Trim(Selection.item(ir, 1))) If L < 3 Then GoTo nextrow '-- this is where SepLastTerm differs from SepTerm For im = L - 1 To 2 Step -1 If Mid(checkx, im, 1) = " " Then Selection.item(ir, 1) = Left(checkx, im - 1) Selection.item(ir, 1).Offset(0, 1) = Trim(Mid(checkx, im + 1))

GoTo nextrow End If Next im nextrow: Next ir terminated: Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub Notes for separating lastnames: You will probably have to rework your results afterwards, but you might save some trouble if you have a lot of prefixed last names by changing such names containing "Mac ", "van " and "von " to "Mac_", "van_" and "von_" beforehand and then removing the unscore later. Not a problem for anything I've writtern here but also be aware of names like O'Connor. Watch out for changes to capitalization and to exceptions -- it always comes down to you have to know your data, but such steps may save you some time. In the coding to go with this page are some additional subroutines and functions mainly related to lastnames or separating the last word. SepLastName for people's names, SepLastWord uses StrReverse new in Excel 2000, LastWord function uses StrReverse. Another concept is an example of a VBA Script function, resubstr.join by Harlan Grove which is interesting but has too many assumptions on data fitness for my use. Notes for separating zipcodes: Format the column ahead of time as text; otherwise, you will experience 4 and 5 digit numbers sorted as numbers without leading zero and appearing ahead of text entries of nine digit numbers with hyphens. Numbers sort before text. When sorting be sure to select all of the columns involved not just the columns to be sorted on (Data-->Sort) Additional zipcode information may be found with MailMerge documentation but most of fixing and separating zip codes will continue to be found here on this page. Briefly Mail Merge can accept data from the first worksheet tab in your Excel file as the data (database) and use it to create name and address labels, and/or to create letters. Columns must have headings for Mail Merge to function. Start blank (new) word document, Tools --> Mail Merge --> labels etc. See FixUSzip5 on this page for additional information. Notes for separating City, State, zipcode: Some cities have more than one word in their names, and some states have more than one word in their names, so Text to Columns may not work for your data, but you can take some steps to save time later by first combining some prefixes or combinations into one word such as changing "New " to "New_" as in "New York" to "New_York", and "Washington D.C." to "Washington_D.C." > ahead of time doing the separation and then removing the underscores later. and then split from the right using SepLastTerm (above) into an inserted empty column to split off the zip code, repeat to split off the state, hopefully you are done after resubstituting underscore for a space in the city and state columns. Some Worksheet Solutions equivalent to SepLastTerm

AN=587462062 David Hager, 2000/02/19 This is an Array Formula. Hold down the Ctrl and Shift keys when entering this formula. The formula can be replicated down using the fill-handle.
=MID(A1,MAX((MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1)=" ")*ROW(INDIRECT("1:"&LEN(A1))))+1,255) AN=587474402 George Simms, 2000/02/19 like the previous

example this is an array formula Ctrl+Shift+Enter so that you see braces on the formula line surrounding entire formula. (possible errors #VALUE! if not entered as an array formula, or #N/A! if there are not at least two words)
=RIGHT(A2,MATCH(" ",MID(A2,LEN(A2)-ROW(INDIRECT("1:"&LEN(A2))),1),0))

AN=587474402 Chip Pearson has a webpage First and Lastnames none of the examples match SepLastTerm though. Splitting an Address line apart that is all together This is about the worst case, without any commas for separation and no distinction separation between street, and town.
200 Flinders St Melbourne VIC 3000

wanted as A B C D E

1 200 Flinders St Melbourne VIC 3000


[Ctrl+t] Sub SplitAddressing() '-- include St Ave Ct Cir Blvd etc. as needed Columns("A:A").Replace What:=" St ", _ Replacement:=" St,", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False Columns("A:A").Replace What:=" Ave ", _ Replacement:=" Ave,", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False Columns("A:A").Replace What:=" Ct ", _ Replacement:=" Ct,", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False '-- if you had US states that you don't want to separate Columns("A:A").Replace What:=" New York ", _ Replacement:=" New_York", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False Columns("A:A").TextToColumns DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _ :=Array(Array(1, 1), Array(2, 1)) Columns("B:B").Insert Shift:=xlToRight Columns("A:A").Select SepTerm

Columns("C:C").Select SepLastTerm Columns("d:d").Insert Shift:=xlToRight Columns("C:C").Select SepLastTerm Columns("A:E").EntireColumn.AutoFit End Sub

Also see posting 2002-04-18 by Myrna Larson.

Some additional worksheet function and macro usage (#morestuff)


Rearrangements based on comma (#recomma)
Retaining an alphabetized listing as lastname, first names probably makes the most sense, as long as only a single comma is used. This allows for sorting of names. A simple rearrangement is possible then with a function or macro. The following worksheet solution was posted by Tom Ogilvy to split text at first comma to utilize the portion after the comma as a new sort field.
=RIGHT(A12,LEN(A12)-FIND(",",A12))

This is set up to work on the address in cell A12. To remove the space after the comma also
=RIGHT(A12,LEN(A12)-FIND(",",A12+1))

Then drag fill this formula down the column. Solutions to converting Williams, John B. to John B. Williams. The one with TRIM works because it can handle zero or more spaces after the comma.
=MID(A2,FIND(",",A2)+2,LEN(A2)-FIND(",",A2))&" "&LEFT(A2,FIND(",",A2)-1) =MID(A2,FIND(",",A2)+2,255) & " " & LEFT(A2,FIND(",",A2)-1) =TRIM(MID(A2,FIND(",",A2)+1,255) & " " &LEFT(A2,FIND(",",A2)-1))

Worksheet solution to split at a comma removing any space immediately after the comma.
A12: Van Leeuwen, Joseph H. B12: =LEFT(A12,FIND(", ",A12)-1) C12: =TRIM(RIGHT(A12,LEN(A12)-FIND(",",A12)))

REPLACE in a macro

(#ReplaceCRLF)

You might want to make a global replacements in selected cells similar to Ctrl+H, such as removal of commas. The following code removes Carriage Return (x'0D') and Line Feed (x'0A') from the selected range. Tab is x'09'. For more information see Excel HELP --> Index --> Visual Basic Code --> Worksheet Functions
Sub ReplaceCRLF() 'Bill Manville Thu, 1999-02-04 Selection.Replace Chr(13)," ",xlPart Selection.Replace Chr(10)," ",xlPart End Sub

'x1Part apply to within cells (default) 'xlWhole apply to entire cell content

REPT Worksheet Function

(#REPT)

REPT repeats text a given number of times, in the example below spaces are repeated. Use of REPT was suggested by Thomas Ogilvy (1998-08-05) as a means of sorting the numeric street numbers utilizing a separate column. At first I thought it didn't sort when I attempted to sort on the single column without including the column referred to -- after all it was only test data and I didn't care whether it remained intact or not. These extra spaces can only be seen properly in a fixed font such as "Courier". For sorting you might consider also making the street fixed length and have it sort before the numeric portion. A
102 Wash. Blvd. 1024 Wash. Blvd. 1027 Wash. Blvd.

B
102 Wash. Blvd. 1024 Wash. Blvd. 1027 Wash. Blvd.

=GetFormula(B1)
=REPT(" ",6-SEARCH(" ",TRIM(A1)))&TRIM(A1) =REPT(" ",6-SEARCH(" ",TRIM(A2)))&TRIM(A2) =REPT(" ",6-SEARCH(" ",TRIM(A3)))&TRIM(A3)

00026 Wash. Blv 00026 Wash. Blv =REPT(" ",6-SEARCH(" d. d. ",TRIM(A4)))&TRIM(A4)

VAL Function in VBA

(#VAL)

The VAL function extracts leading digits ignoring embedded spaces.


Function NumVal(n) As Double NumVal = VAL(n) 'obtains leading number value ' -- Dana DeLouis 200011-29 End Function 123abc678 Result --> 123

A112 Result --> 0 12 a 67 b 12 Result --> 12 12 45 Result --> 1245

Extract numbers from a cell


The number must be contiguous. Non-contiguous characters in the ten characters examined result in #Value! error.

One way, put the below formula in B1 if "AB12FG" is in cell A1, copy it down as long as needed. Peo Sjoblom <[email protected]> 2001-07-09 in worksheet.functions
=MID(A1,MATCH(FALSE,ISERROR(1*MID(A1,ROW(INDIRECT("1:10")),1)),0),10SUM(1*ISERROR(1*MID(A1,ROW(INDIRECT("1:10")),1))))*1

*Note that it is an array formula and should be entered with Ctrl+Shift & Enter

Testing Things on This Web Page

(#markcells)

A short demonstration of items on this page can be accomplished by installing each of the macros on this page -- Join(), ReversI(), SepTerm(), MarkCells(), and MarkSepAreas(). Each of these macros are frequently used in testing. MarkCells() will destroy previous contents within Selection RANGE. Each cell will be identified with it's address when MarkCells was invoked. The examples in Samples below, and in Delete Cells/Rows in Range, based on empty cells utilized MarkCells. Some similar items of interest are AAA_ZZZ macro will generate AAAA up to ZZZZ within a selected range(s). Also of interest is a UDF by Myrna Larson that increments strings See related area below. Suggested Toolbar menu item [Mark cells with cell address]
Sub MarkCells() 'David McRitchie 1998-08-17 [Mark cells with cell address] Documented 'with Join() in http://www.mvps.org/dmcritchie/excel/join.htm Application.ScreenUpdating = False Application.Calculation = xlCalculationManual '--Dim iX as Long '--For iX = 1 To Selection.Count '(0,0) below is same as (False, False) '-- Selection.Item(iX) = "'" & Selection.Item(iX).AddressLocal(0, 0) '--Next iX Dim cell As Range For Each cell In Selection '(0,0) below is same as (False, False) cell.Value = "'" & cell.AddressLocal(0, 0) Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

The following is a little shorter and eliminates a Dim statement in the old code now commented out. A single quote inside double quotes is included in both examples. In Excel 97 and above the For Each version will handle multiple selected areas.
For Each Cell In Selection Cell.Value = "'" & Cell.AddressLocal(0, 0) Next Cell

The Worksheet Function equivalent is =ADDRESS(ROW(),COLUMN(),4) but the value will change when it is moved to match the cell it is in. The use of MarkCells is to show where the cell was originally after moving things around, not where it currently resides after moving things around. You can place 'A1 into cell A1 and fill down to be more like the macro MarkCells, and when you move things around it will show where it used to be just like you would see if you had used the macro.

MarkSepAreas()

(#marksepareas)

Mark Separate Areas (MarkSepAreas) is similar to MarkCells but has been enhanced to process separate areas. Processing of separate areas is based on a posting by Alan Beban that was actually filling out an array, I thought a minor modification might make for a more interesting version of MarkCells() above.
Sub MarkSepAreas() 'David McRitchie 1999-06-03 Mark cells with cell address and 'area number. Enhanced based on Alan Beban code 1999-06-03. 'Documented with Join() 'in http://www.mvps.org/dmcritchie/excel/join.htm Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim i As Long, j As Long For i = 1 To Selection.Areas.Count For j = 1 To Selection.Areas(i).Count Selection.Areas(i)(j).Value = "'" _ & Selection.Areas(i)(j).AddressLocal(0, 0) & "-" & i Next Next Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Note the areas are the areas in the order in which they were added to the selection. Alan's original code would produce an array which I believe might be something conceptually like: $F$2, $G$3, $H$4:$I$4, $I$5, $H$5, $H$7, $I$7, $H$9:$I$9 F2-1 G3-2 H4-3 I4-3 H5-5 I5-4 H7-6 I7-7 H9-8 I9-8
Usually you make a single selection of multiple cells by left-clicking on a cell and dragging without releasing the button to make your selection. The range is a rectangular area. The Ctrl key is use if you want to add additional selection areas. For worksheet things (no macros) it won't make any difference how many separate (rectangular) areas you created when do things like assign a color, or format. With a macro you can process each area separately and until Excel 2000 that is what you had to do. Excel 2000 allows you process all selections as if they were one or as in MarkSepAareas you can still process each area in the same manner as had to be done in previous versions.

Fill Cells with Sequential numbers (#fillsequence)

Cells are ordered left to right, next row -- left to right, etc. You can have multiple selection ranges in Excel 2000. If the ranges overlap you will have missing numbers as each range is filled in the order it was selected and filled in before continuing to the next range.

AB C D E Suggested Toolbar menu item [Fill Sequence 1-23] Sub FillSequence() Dim cell As Range Dim i As Long For Each cell In Selection i=i+1 cell.Value = i Next cell End Sub

1 2 1 2 3 3 4 4 5 9 10 5 7 11 15 16 6 13 17 18 7 22 19 21 Colors depict multiple ranges

Worksheet Equivalent as formulas Not suitable for test data because it will show the current address after further manipulation, but here is something to keep your interest.
=CELL("address",c14) Displays as $C$14 =CELL("address",offset(c14,-1,0)) =ADDRESS(14,3) equals "$C$14", relative form available with 4 as 3rd =ADDRESS(ROW(C14),COLUMN(C14),4) equals "C14" operand

Filling in Cell Comments for Testing


See Placing Formulas into Cell Comments or Placing Displayed Text into Cell Comments

Propagation using the Fill Handle

(#fillhandle)

A single cell or group when propagated using the fill-handle will increment the numbers and numeric suffixes (A1, B1). Dates are numbers and will be propagated according to how you start the sequence. After using Mark Cells you can propagate down, but because the numbers would increment across a row, you would not fill in this sequence to the right because you would be incrementing the numbers instead of the letters (letters do not increment without formulas). Fill in a series for a growth trend (from HELP --> wiz --> fill handles) 1 Select at least two cells that contain values on which you want to base the trend. 2 Hold down the right mouse button and drag the fill handle in the direction you want to fill. 3 Release the mouse button and then click Growth Trend on the shortcut menu. Additional information on Fill Handle

animation of fill-handle, wugnet tips Fill Handle page on this site.

Transpose data in Column A to Row 1 for titles

The cells in column A will be transposed to Row 1 beginning at cell B2, the column A will be cleared out, and columns A and Row 1 together will be made boldface. Saving of the file is required to fix the lastcell (can be tested with Ctrl+End). The source is shown in blank which gets cleared and their result is shown in blue. A B C D E F G H I J K L M N O P Q R S T U V 1 A1 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16 A17 A18 A19 A20 A21 2 A2 Sub TransposeColumnA() 3 A3 'David McRitchie, 2000-11-30 misc, 4 A4 ' http://www.mvps.org/dmcritchie/excel/join.htm 5 A5 Range("A1").Activate Cells(Rows.Count, ActiveCell.Column).End(xlUp).Select 6 A6 Range("A1", ActiveCell.Address).Copy 7 A7 Range("B1").Select Selection.PasteSpecial Paste:=xlAll, _ 8 A8 Operation:=xlNone, SkipBlanks:=False, _ 9 A9 Transpose:=True Columns("A:A").Select 10 A10 Selection.Clear 'Clear and save to 11 A11 ActiveWorkbook.Save 'Correct lastcell location 12 A12 Range("A:A,1:1").Select Selection.Font.Bold = True 13 A13 Range("B2").Select 14 A14 End Sub 15 A15 Compare the first part of this macro to macro below found in: http://www.mvps.org/dmcritchie/excel/toolbars.htm 16 A16 17 A17 18 A18 19 A19
Sub GotoBottomOfCurrentColumn() 'Tom Ogilvy 2000-06-26 Cells(Rows.Count, ActiveCell.Column).End(xlUp).Select End Sub

Let the testing demonstration begin (#demo)


1. Create a new worksheet 2. Select range a1:f25 3. Populate with data using MarkCells macro. Possibly with Toolbar menu item [Mark cells with cell address] 4. Rearrange items in list, select range a1:f20, invoke ReversI() macro. Tools --> Macro --> (select ReversI) --> Run. 5. Restore original arrangement by reinvoking ReversI() with same range. 6. Select range a1:f25 7. Join columns into first selected column using Join(). Possibly invoked with shortcut key [Ctrl + j ]. 8. Select range a1:a25. Use Data --> Text to Columns to resplit columns. Use delimited by Space. 9. Select range a1:c25. Use Join. With a little imagination the resulting format could be a street address (1082 Washington Blvd.), in fact you could change cell A1 to that if you like. 10. Select range a1:b25. Use SepTerm(). Only the first column is actually used, the adjacent column to the right should be empty. 11. Test is ended. If you like you may select b1:b25 and invoke SepTerm()

Samples

(#samples)

Use of MarkCells A B C D 1 A1 B1 C1 D1 2 A2 B2 C2 D2 3 A3 B3 C3 D3 4 A4 B4 C4 D4 5 A5 B5 C5 D5 6 A6 B6 C6 D6

Use of ReversI A B C D 1 D6 C6 B6 A6 2 D5 C5 B5 A5 3 D4 C4 B4 A4 4 D3 C3 B3 A3 5 D2 C2 B2 A2 6 D1 C1 B1 A1

Use of Join on Original A BC D 1 A1 B1 C1 D1 2 A2 B2 C2 D2 3 A3 B3 C3 D3 4 A4 B4 C4 D4 5 A5 B5 C5 D5 6 A6 B6 C6 D6 after JOINROWS() A B C D 1 A1 B1 C1 2 A2 B2 C2 A3 B3 C3 3 A4 B5 C4 C5 4 A6 B6 C6 5 A7 B7 C7

Use of SepTerm A B C D 1 A1 B1 C1 D1 2 A2 B2 C2 D2 3 A3 B3 C3 D3 4 A4 B4 C4 D4 5 A5 B5 C5 D5 6 A6 B6 C6 D6

before JOINROWS() A B C D 1 A1 B1 C1 2 A2 B2 C2 3 A3 B3 C3 4 A4 C4 5 B5 C5 6 A6 B6 C6 7 A7 B7 C7 Use of Lastname() Before After Donald Duck Duck, Donald Mouse, Mickey Mouse, Mickey Minnie Mouse Mouse, Minnie Name and Address List before SepLastTerm A B C 1 Addressee Address City, State zipcode 2 John Doe 13 Main St Hartford, CT 06111 3 Bill Smith 26 Elm St Erie, PA 16501-1234 D E

Use of firstname() Before After Duck, Donald Donald Duck Mouse, Mickey Mickey Mouse Mouse, Minnie Minnie Mouse Name and Address List after SepLastTerm on Col C A B C D E 1 Addressee Address City, State zipcode 16501-1234 2 John Doe 13 Main St Hartford, CT 06111 3 Bill Smith 26 Elm St Erie, PA

When separating zip codes format the receiving column as text beforehand, since some zip codes begin with zero.

Rotate Selection Area 90 degrees

(#RotateCWx)

Main Samples Area, begins immediately above. RotateCW() Before A B C 1 E1 E2 E3 2 D1 D2 D3 3 C1 C2 C3 RotateCW() After Rows flipped A B C D 1 A1 A2 A3 A4 2 B1 B2 B3 B4 3 C1 C2 C3 C4 RotateCW() After TRANSPOSE A B C D E 1 A1 B1 C1 D1 E1 2 A2 B2 C2 D2 E2 3 A3 B3 C3 D3 E3

D E4 D4 C4

4 B1 B2 B3 B4 5 A1 A2 A3 A4

4 D1 D2 D3 D4 5 E1 E2 E3 E4

4 A4 B4 C4 D4 E4

Formatting and Formulas are preserved Good Luck! Happy EXCELing.

Text to Columns

(#Txt2Cols)

Splitting on Space: With all the emphasis here on macros don't forget Data-->Text to columns, and especially keep in mind that there is a both a delimited and a fixed option. The fixed option will allow you to split a single word in each row into multiple cells on each row. Splitting on a single comma: It is possible to eliminate the extra space after the comma strictly with Text to Columns. Personally I would use my TrimALL macro since I have it set up. Data, Text to Columns, comma delimiter to separate into the two columns (dependent on there being only one comma in the cell) Data, Text to Columns, fixed width double click or drag the break line off the window to remove, then with only one column use the Finish button. Thank goodness for backups the remainder of this document starting from within the next topic was discovered missing 2004-11-08 and recovered from a backup from 2004-08-27.

Populating a Table based on number of rows and columns (#MultTab)


The following example will generate a multiplication table starting at cell A1.
Sub MultTable() noCols = InputBox("Number of columns") noRows = InputBox("Number of Rows") Dim ir as Long, ic as Long For ir = 1 To noRows For ic = 1 To noCols cells(ir, ic).Value = ir * ic Next ic Next ir End Sub

AB C D 1 1 2 3 2 11 2 3 3 22 4 6 4 33 6 9 5 4 4 8 12 6 5 5 10 15

E 4 4 8 12 16 20

AB C D E F 1 1 2 3 4 5 6 2 2 4 6 8 10 12 3 3 6 9 12 15 18 4 4 8 12 16 20 24 5 5 10 15 20 25 30 6 6 12 18 24 30 36

G 7 14 21 28 35 42

B2: =$A2*B$1

A1: =ROW( )*COLUMN( ) and then use the fill handle

The following example will generate an addition table starting at the currently active cell.

Sub AdditionTab() noCols = InputBox("Number of columns") noRows = InputBox("Number of Rows") Dim noCOls as Long, noRows as Long Dim ir as Long, ic as Long Dim ics as Long, irs as Long ics = ActiveCell.Column irs = ActiveCell.Row 'Starting at the active cell For ir = 0 To noRows - 1 For ic = 0 To noCols - 1 cells(ir + irs, ic + ics).Value = ir + ic Next ic Next ir End Sub

ABCD E F G H 1 0123 4 5 6 7 2 1234 5 6 7 8 3 2345 6 7 8 9 4 3 4 5 6 7 8 9 10 5 4 5 6 7 8 9 10 11 6 5 6 7 8 9 10 11 12 7 6 7 8 9 10 11 12 13

I 8 9 10 11 12 13 14

Worksheet Solution: A1: =Row( )-1 + Column( )-1 and then use the fill handle

Another approach to generate your Multiplication Table and Addition Table is to use the fill handle with formulas. Multiplication Table starting in cell A1: =(Row()-1)*(Column()-1) Addition Table starting in cell A1: =Row()-1+Column()-1

Separation of Lastname, Firstname middlenames (#sep3terms)


Sub Sep3Terms() 'David McRitchie 1999-03-11 will be documented in ' http://www.mvps.org/dmcritchie/excel/join.htm 'Separate lastname, firstname middlenames into 3 entities 'Work on first column, cell to right must appear to be blank '--Application.ScreenUpdating = False 'On Error Resume Next iRows = Selection.Rows.Count Set lastcell = cells.SpecialCells(xlLastCell) mrow = lastcell.Row If mrow < iRows Then iRows = mrow 'not best but better than nothing For ir = 1 To iRows If Len(Trim(Selection.item(ir, 1).Offset(0, 1))) + _ Len(Trim(Selection.item(ir, 1).Offset(0, 2))) + _ Len(Trim(Selection.item(ir, 1).Offset(0, 3))) <> 0 Then iAnswer = MsgBox("Found non-blank in adjacent 3 columns -- " _ & Selection.item(ir, 1).Offset(0, 1) & " -- in " & _ Selection.item(ir, 1).Offset(0, 1).AddressLocal(0, 0) & _ Chr(10) & "Press OK to process those than can be split", _ vbOKCancel) If iAnswer = vbOK Then GoTo DoAnyWay GoTo terminated End If Next ir DoAnyWay: Application.ScreenUpdating = False For ir = 1 To iRows 'If Len(Trim(Selection.item(ir, 1).Offset(0, 1))) <> 0 Then GoTo nextrow checkx = Trim(Selection.item(ir, 1)) Ipos = InStr(checkx, ",") If Ipos = 0 Then

lastname = checkx firstnames = "" Else lastname = Left(checkx, Ipos - 1) firstnames = Trim(Right(checkx, Len(checkx) - Ipos)) End If Ipos = InStr(firstnames, " ") If Ipos = 0 Then firstname = firstnames middlename = "" Else firstname = Left(firstnames, Ipos - 1) middlename = Right(firstnames, Len(firstnames) - Ipos) End If Selection.item(ir, 1).Offset(0, 1) = firstname Selection.item(ir, 1).Offset(0, 2) = middlename Selection.item(ir, 1).Offset(0, 3) = lastname Next ir terminated: Application.ScreenUpdating = True End Sub

Smith iii Smith iii Smith iii Smith iii Smith, Smith Smith, John A. John A. Smith Smith,, , Smith Smith,, John A. , John A. Smith Smith,,O B ,O B Smith Smith,J. Jones J. Jones Smith Smith,J. Jones J. Jones Smith Smith,J. Jones,DDS,Dr J. Jones,DDS,Dr Smith Smith,O O Smith Smith,O O Smith Smith,O B O B Smith Chip Pearson also has a page on Working with First and Last Names: http://www.cpearson.com/excel/FirstLast.htm and another on parsing US style phone numbers. (both different approaches from what I've shown on this page)

Return string after last "/" character


=AFTLAST(E22) Function AFTLAST(cell As Range, findchar As String) As String Application.Calculation = xlCalculationManual 'in XL97 Dim i as Integer For i = Len(cell) To 1 Step -1 If Mid(cell, i, 1) = findchar Then AFTLAST = Mid(cell, i + 1, 99) Exit Function

(#aftlast)

End If Next i AFTLAST = cell ' or aftlast="" depending on what you want Application.Calculation = xlCalculationAutomatic 'in XL97 End Function

Return string after first "/" character


Remove everything to left of first "/"
=IF(ISERR(FIND("/",E22)),E22,MID(E22,FIND("/",E22,1)+1,99)) or =IF(ISERR(FIND("/",E22)),"",MID(E22,FIND("/",E22,1)+1,99)) depending on whether you want cell value or nothing when "/" is not present.

Strip Left 2 characters from cells in Selected Range (#stripL2)


Sub StripL2() 'Strip left two positions from cell in selection range 'SpecialCells will limit the range to the used area within Dim cell As Range For Each cell In Selection.SpecialCells(xlConstants) cell.Value = Mid(cell.Value, 3) Next cell End Sub

Remove Excess hyphens in TEXT cells


DCK43V--FS-4824-G3--SWS--7224--S

(#remxhyps)

This macro will remove doubled hyphens as well as prefixed and suffixed hyphens for TEXT value within a selected range. Will ignore numbers like -7. TRIM which removes spaces will be performed on all text cells that contain at least one hyphen within the selected area.

The complete thread AN=590672177 includes an XL95 version with changes to Calculation, SpecialCells, and Replace.
Option Explicit Sub REMXHYPS() 'David McRitchie 2000-02-28 excel.programming 'hyphen removals of dups, prefixed, suffixed, and trim results 'updated based on George Clark's simpler Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim temp As String Dim cell As Range For Each cell In Selection.SpecialCells(xlCellTypeConstants, 2) 'above limits to constants which are TEXT If InStr(1, cell.Value, "-") Then 'Insure possibility of change temp = Trim(cell.Value)

While InStr(temp, "--") > 0 temp = Replace(temp, "--", "-") Wend If Right(temp, 1) = "-" Then temp = Left(temp, Len(temp) - 1) If Left(temp, 1) = "-" Then temp = Right(temp, Len(temp) - 1) cell.Value = Trim(temp) End If Next Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub

Single Quote or prefix add/remove for text or for formulas (#squote)


SQUOTE_Add will insert a single quote in front of a formula, rendering it as a comment.
Sub SQUOTE_add() 'David McRitchie 2000-08-05 notposted 'http://www.mvps.org/dmcritchie/excel/join.htm#squote Application.ScreenUpdating = False Application.Calculation = xlManual Dim cell As Range For Each cell In Intersect(Selection, ActiveSheet.UsedRange) If Len(Trim(cell)) > 0 Then _ if left(cell.formula)="=" then cell.Value = "'" & cell.Formula Next cell Application.Calculation = xlAutomatic 'xlCalculationAutomatic Application.ScreenUpdating = False End Sub

insertprefix will insert a prefix of your choice in front of TEXT, which is what you see as opposed to values, or formulas.
Sub insertprefix() 'David McRitchie 2000-08-05 posted 'http://www.mvps.org/dmcritchie/excel/join.htm#squote Application.ScreenUpdating = False Application.Calculation = xlManual Dim cell As Range Dim myPrefix As String myPrefix = "'" myPrefix = InputBox("Supply prefix character(s)", "Supply prefix", myPrefix) For Each cell In Intersect(Selection, ActiveSheet.UsedRange) If Len(Trim(cell)) > 0 Then _ cell.Formula = myPrefix & cell.Text Next cell Application.Calculation = xlAutomatic 'xlCalculationAutomatic Application.ScreenUpdating = False End Sub

SQUOTE_Remove will remove a single quote in front of a formula, rendering it back as a formula. The single quote cannot be detected by with cell.value nor with cell.formula, so there is a little trick used here with VarType(variable), where 8 indicates a string, see GetFormulaI on my Formula page.

Sub SQUOTE_remove() 'David McRitchie 2000-08-05 notposted 'http://www.mvps.org/dmcritchie/excel/join.htm#squote Application.ScreenUpdating = False Application.Calculation = xlManual Dim cell As Range For Each cell In Intersect(Selection, ActiveSheet.UsedRange) If VarType(cell) = 8 Then cell.Formula = cell.Formula 'note the squote is not easily detectable Next cell Application.Calculation = xlAutomatic 'xlCalculationAutomatic Application.ScreenUpdating = False End Sub

Reproduce Formula in ActiveCell to selected ranges(s) -- (#reproduceactive)


Reproduce (copy) same formula unchanged to other selected cells in the sheet. Since the active cell is the one that will get reproduced you should select it last if multiple ranges are selected. In fact you can reselect ranges -- the duplication won't harm anything it will just take a little longer. The active cell will be reentered but that won't matter. Select multiple ranges with the help of the Ctrl key. In Excel 2000 the macro is very simple because Excel 2000 includes all separate ranges. Prior to Excel 2000, one would have to cycle through the separate ranges. Example of cycling through multiple ranges can be seen in the MarkSepAreas macro.
Sub reproduceactive() Dim activecellformula As String Dim cell As Range Dim x As Integer If Selection.Count > 100 Then x = MsgBox("Perhaps you don't really " _ & "want to do this for " _ & Selection.Count & " cells", _ vbOKCancel, "Reproduce active cell " _ & " through selection") If x <> 1 Then Exit Sub End If activecellformula = ActiveCell.Formula For Each cell In Selection cell.Formula = activecellformula Next cell End Sub example: A1: 'a1 B1: '--b1 F1: =A1 & B1 select multiple ranges: B3:F8, C10:E17, D1 invoke macro ReproduceActive

Addition of Prefixes and Suffixes

(#make_indirect)

So far just have Make_INDIRECT for lack of a form that would be needed. Make_INDIRECT will wrap =INDIRECT() around simple assignment statements so that you can refer to specific cells in another (data) sheet and not have things rearranged by insertion/deletions of the data sheet. =Sheet1!A3 becomes =INDIRECT("Sheet1!A3")
Sub Make_INDIRECT() 'David McRitchie 2000-10-12 notposted 'http://www.mvps.org/dmcritchie/excel/join.htm#indirect Application.ScreenUpdating = False Application.Calculation = xlManual Dim cell As Range On Error Resume Next For Each cell In Intersect(Selection, ActiveSheet.UsedRange) If Left(cell.Formula & " ", 1) = "=" Then If Left(cell.Formula, 10) <> "=INDIRECT(" Then If InStr(1, cell.Formula, "!", 0) Then If InStr(1, LCase(cell.Formula), "getformula", 0) = 0 Then cell.Formula = "=indirect(""" & _ Mid(cell.Formula, 2, 9999) & """)" End If End If End If End If Next cell Application.Calculation = xlAutomatic 'xlCalculationAutomatic Application.ScreenUpdating = False End Sub

Remove Prefix

(#remove_prefix)

The following will remove Prefix from cells with TEXT content in a selection.
Sub Remove_Prefix() 'David McRitchie 2001-08-27 excel.programming 'prefix removal Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim temp As String Dim cell As Range Dim xPre As String xPre = InputBox("Supply Prefix to be removed:", _ "Prefix Removal", "401 1") If xPre = "" Then GoTo done On Error GoTo done For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlCellTypeConstants, 2)) 'above limits to constants which are TEXT If Left(cell.Value, Len(xPre)) = xPre Then cell.Value = Mid(cell.Value, Len(xPre) + 1) End If Next

done: Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub

Create formulas in selected cells, with address substitution for word cell (#insertcellreplacement)
The following would also work for the previous example of INDIRECT by changing the default entry. The following subject to modification would insert a link to book [ss.xls]'Sheet7'cell for a HYPERLINK and as a value, where cell would be substituted for the current cell address. Sub InsertCellReplacement() 'David McRitchie, misc, 2001-05-23 ' http://www.mvps.org/dmcritchie/excel/join.htm Dim cell As Range Dim V As String, vv As String Dim i As Integer, j As Integer V = "=HYPERLINK(""[ss.xls]'sheet7'!cell"",[ss.xls]sheet7!cell)" V = InputBox("oportunity to change your formula" _ & vbCR & "the word cell will be substituted with cell address", _ "Your call is important to us", V, vbOKCancel) If V = "" Then GoTo terminate For Each cell In Selection vv = V For i = 1 To 3 j = InStr(1, vv, "cell") If j = 0 Then GoTo vDone vv = Left(vv, j - 1) & cell.Address(1, 1) & Mid(vv, j + 4, 999) Next i vDone: cell.Formula = vv Next cell terminate: End Sub

Cell addressing in VBA

(#vbacell)

Since there are several examples on this page, this seems about as good a place as any to include the following information. Find the numeric column number equivalent for Column "AB".
MsgBox "Numeric equivalent for AB is " & Range("ab" & "1").Column

Find Column number of the selected cell or the last cell.


Set lastcell = Cells.SpecialCells(xlLastCell) lRows = lastcell.Row lCols = lastcell.Column Row = activecell.row Col = activecell.column

Find Column letters of the selected cell Columns run A through IV (1-256), length is 1 for < 27, or 2 above 26.
= Left(ActiveCell.Address(0, 0), (ActiveCell.Column < 27) + 2)

Even simpler is one from Dana DeLouis, 2001-03-04 in programming


= Split(ActiveCell.Address, "$")(1) 'For Column Letter = Split(ActiveCell.Address, "$")(2) 'For Row Number

Finding the Relative Address of a cell. Assumes you have A1 addressing: Tools --> Options --> General --> with R1C1 off Place address of cell into itself as a text entry -- see MarkCells example above.
Selection.Item(iX) = "'" & Selection.Item(iX).AddressLocal(0, 0)

Followup example:
Sub test10() 'will display CV as equivalent of 100, and 28 for AB C = 100 MsgBox "Alpha equivalent for Col " & C & " is " & _ Left(cells(1, C).AddressLocal(0, 0), _ Len(cells(1, C).AddressLocal(0, 0)) - 1) MsgBox "Numeric equivalent for AB is " & Range("ab" & "1").Column End Sub

Worksheet Example of converting column number to a Letter Will convert numbers 1 to 256 to Excel column letters A to IV.
256 IV =LEFT(ADDRESS(1,A1,4),LEN(ADDRESS(1,A1,4))-1) 1 A =LEFT(ADDRESS(1,A2,4),LEN(ADDRESS(1,A2,4))-1) 2 B =LEFT(ADDRESS(1,A3,4),LEN(ADDRESS(1,A3,4))-1) 3 C =LEFT(ADDRESS(1,A4,4),LEN(ADDRESS(1,A4,4))-1) 4 D1 =ADDRESS(1,A5,4) **ADDRESS(row,column)**

Shortcut Keys in Excel (#shortcut)


Shortcuts are entirely optional. A shortcut key can be assigned to a macro using: Tools --> Macro --> (select a macro) --> Options. Excel will Warn you if you attempt to utilize a short cut key already in use -- it will change the form of assignment for instance. You will have to remember them or write them down somewhere. I highly recommend creating a sheet for your MS Excel installed shortcut keys so that you can use FIND to find a shortcut yourself. You could even add your own at the bottom. Also recommend creating another sheet for function keys. More information on Viewing, Listing and Creating Shortcut Keys.

Related Items

(#related)

How to install/use a macro can be found on my formula page (formula.htm). A simplified version of installing/using macros can be found on my Getting Started with Macros page (getstarted.htm). Dates used in text usually relate to posting dates in Google Advanced Usenet Search for microsoft.public.excel* newsgroups. AAA_ZZZ macro, David McRitchie, creates a sequence of AAAA up to ZZZZ in the selected range. Shows on Status Bar, and DoEvents to relinquish control to operating system during it's run. Excel 2000 allows multiple ranges to be treated in order. In the same thread Bernie Dietrich posted a worksheet formula that would increment from AAA to ZZZ.

Combine rows, based on Column A posted by Patrick Molloy combines B column as comma separated values for rows that have same column A value (merging cells then deleting rows). (See sumdata.htm for similar things.) Combine multiple row groupings into one row per group by Tom Ogilvy "Re: Copy value and paste to multiple cells" Builddata, from one worksheet combined into another. Combine multiple sheets/workbooks into one workbook or into one sheet, Bernie Dietrick, 2001-03-13. ExtractDigits, User Defined functions posted by Harlan Grove in worksheet.functions, (thread), User Defined Function, extract first set of consecutive digits from a string. Treat as a number if found as an empty string if none found (i.e., g25abc16 would return 25). In an older thread is a means to extract set of digits from left/middle/right using an array formula, but it fails if you have two sets of digits in the same string (i.e. g25abc16 would fail). The UDF code for ExtractDigits and ExtractDigits_andDashes, and the subroutine LeaveDigits_andDashes can be found in the code for this page (join.htm). Fill in the Empty Cells, this macro will fill in empty cells with the content of the cell above it, providing the cell above is also within the selection range. See Q89228 -- Excel: AutoFill Rules for Creating a Series IncrementStrings by Myrna Larson. The UDF adds a positive or negative number, N, to the string. If the character at a given position is an upper case letter, it will remain an upper case letter (i.e. Z wraps to A and generates a "carry"); a lower case letter remains a lower case letter (z wraps to a with a carry); digits remain as digits; symbols are skipped. Suggested for catalog and invoice numbers (more on invoice numbers below). Adding 17 to the string AB-0a0 gives AB-0b7 The maximum value for that "number" would be ZZ-9z9, and the minimum value AA-0a0. A string of ##'s indicates overflow or underflow. Insert ROW using a Macro, the macro described will insert row(s) below a selected row or cell. The advantage of using a macro is that the formulas will be copied, but not the data; providing a more reliable method of inserting lines than simply inserting a row and then dragging a row with formulas and data into an inserted empty row. Join Columns B&C when Column M not empty, fixing up a name and address listing when lastname is comprised of two names. Obviously this is a very special situation, this is not how such data would normally be identified. Mail Merge, Using Mail Merge with data from ExcelExcel can be used to supply the data to mailmerge in MS Word. I found this a little tricky first time but have done this from both XL95 and XL2000. Have included information for printing on labels. and references such as Zip+4 Lookup System Name and Address list reformatting, Tom Ogilvy, 2001-03-31, news:#veqMnfuAHA.1568@tkmsftngp04, Take a three column list, Name, Address(3 rows), phone and convert to Name, Address1, Address2, City3, Phone. Column A not occupied indicates a continuation. Push down values in Column if not lowest in row Proper, and other Text changes , PROPER, LOWER (LCase), UPPER (UCase), and TRIM functions. (VBA functions are in parentheses) Reset Last Cell Used Attempts to provide additional information concerning eliminating unused rows at end and unused columns to right of sheet beyond what can be seen in Q134617. Reshape an array of cells. Alan Beban, his array formulas, =ArrayReshape(A1:A100,20,5) Disadvantage compared to other macros is that you have to specify the dimensions. (also see combine into rows earlier) Sequential numbers and invoice numbers , McGimpsey, One common question on the newsgroups is how do I increment a number in my sheet each time I use it, whether it's an invoice, an order form, or some other numbered form. Shortcut keys in Excel Create an Excel Sheet with shortcut keys as a reference that you can find things with the FIND command. SnakeCol, Snaking columns is a frequent request on the Excel Newsgroups. Snaking columns allows you to print several columns on one page. As the macro currently stands you will have to modify the macro to specify some parameters such as number of rows on a page, how many heading lines, how many columns in the original. Sorting, sorting data String Manipulations SUMIF, Primary example uses SUMIF to provide subtotals by date. Syntax and additional examples are also included. Split at first number in a cell (macro), Tom Ogilvy <uIKuAcRZAHA.404@tkmsftngp05> Do While Not IsNumeric(Mid(sStr, i, 1)) ... Summarizing Data, and Auto Filter, Some examples for Auto Filter (Data menu), Conditional Formatting (Format menu), Pivot Table (Data Menu), Subtotals (Data menu) Symbols contains ASCII and EBCDIC tables. TRIMALL macro (on this page) to convert Char(160) and TRIM spaces, which may interfere with sorting. Excel to HTML conversions using macros.

Related Information on Other Sites


Unselecting cells from a selected range: http://www.cpearson.com/excel/unselect.htm Working with First and Last Names: http://www.cpearson.com/excel/FirstLast.htm compare to macros on this page. Excel to HTML conversions using macros. XL2HTML-Konverter for XL5/7 in german language -- hwkkonv.zip by Hans W. Herber and also a really simple conversion to HTML without fonts, alignment etc. simple convert (under 30 lines of code). I used the simple convert for REPT example. The simple conversion will process a preselected range, use of an InputBox to be able to change the output file. It will also place &nbsp; when needed for empty cells. Q181148 -- XL97: Using the File Integration Wizard can be use to join worksheets together, haven't used it and the page does not provide examples but it allows you to combine from sources that Excel can read into one sheet and do some arithmetic operations while doing this. (last update: Thu, 12 May 2005 19:30:57 GMT)

This page was introduced on August 05, 1998.

[My Excel Pages -- home] [INDEX to my site and the off-site pages I reference] [Site Search -- Excel] [Go Back] [Return to TOP]
Please send your comments concerning this web page to: David McRitchie send%20email%20comments

Copyright 1997 - 2004, F. David McRitchie, All Rights Reserved

Delete Cells/Rows in Range, based on empty cells, or cells with specific values
Location: http://www.mvps.org/dmcritchie/excel/delempty.htm Home Page: http://www.mvps.org/dmcritchie/excel/excel.htm Assistance to Install a Macro or User Defined Function on my Formula page.

Delete Empty Cells but don't disturb rows (#DEL95HTMLemptyCells)


The DEL95HTMLemptyCells is designed to clean up the mess that Excel 95 creates when pasting from a web page into Excel. My experience with pasting Excel 95 was that instead of continuing a row across it also frequently jumped down a row besides for what should have been on the same row. The following macro attempts to fix that and is dependent on there being a value in Column A for every row in the original. This macro will move cells up if there is an empty cell above and column A cell is empty. Data at the right tests more than just what can happen with Excel 95 pasting. 1 2 3 4 5 6 7 8 9 A5 B5 C5 D5 E5 F5 G5 10 A6 B6 C6 D6 E6 F6 G6 A B C D E F G A1 B1 C1 D1 E1 F1 G1 A2 B2 C2 D2 E2 F2 G2 A3 B3 C3 D3 E3 F3 G3 A4 B4 C4 D4 E4 F4 G4

Sub DEL95HTMLemptyCells() 'David McRitchie, 2002-08-24, Worksheet Functions ' Move cells up into empty cell below if Column A cell ' on line to be moved up is empty. Application.ScreenUpdating = False Application.Calculation = xlManual '--Excel 95 Dim Rcnt As Long, Ccnt As Long, r As Long, c As Long Dim CurrCell As Range On Error Resume Next Selection.Replace What:=Chr(160), Replacement:=Chr(32), _ LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=True Rcnt = Cells.SpecialCells(xlLastCell).Row Ccnt = Cells.SpecialCells(xlLastCell).Column For r = Rcnt To 2 Step -1 If IsEmpty(Cells(Rcnt, 1)) Then For c = 1 To Ccnt If Not IsEmpty(Cells(r, c)) Then If Not IsEmpty(Cells(r - 1, c)) Then GoTo notthis End If Next c For c = 1 To Ccnt If Not IsEmpty(Cells(r, c)) Then Cells(r - 1, c) = Cells(r, c) End If Next c Cells(r, 1).EntireRow.Delete notthis: End If Next r Application.Calculation = xlAutomatic '--Excel 95 Application.ScreenUpdating = True End Sub

11 A7 12 B7 13 C7 G7 14 D7 F7 15 E7 16 A8 B8 C8 D8 E8 F8 G8 17 A9 B9 C9 D9 E9 F9 G9

1 2 3 4 5 6 7 8 9

A B C D E F G A1 B1 C1 D1 E1 F1 G1 A2 B2 C2 D2 E2 F2 G2 A3 B3 C3 D3 E3 F3 G3 A4 B4 C4 D4 E4 F4 G4 A5 B5 C5 D5 E5 F5 G5 A6 B6 C6 D6 E6 F6 G6 A7 B7 C7 D7 E7 F7 G7 A8 B8 C8 D8 E8 F8 G8 A9 B9 C9 D9 E9 F9 G9

Delete Empty Cells and Cells with Only Spaces (#DelCellsUp)


Warning: This section Deletes Cells, Deleting Rows is in the next section. The DelCellsUp macro will delete all empty cells within the highlighted range and move the cells and formatting up from below. Cells deleted will only be deleted from within range; but cells moved up includes cells from below range.
Sub DelCellsUp() 'David McRitchie 1998-07-17 revised 2002-01-17 ' http://www.mvps.org/dmcritchie/excel/delempty.htm 'Delete Empty Cells and cells with only spaces in range ' and move cells up from below even if not in range 'Will process single range of one or more columns 'Will not remove cells with formulas Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim rng As Range, ix As Long Set rng = Intersect(Selection, ActiveSheet.UsedRange) If rng Is Nothing Then MsgBox "nothing in Intersected range to be checked/removed" GoTo done

End If For ix = rng.Count To 1 Step -1 'CHR(160) is non-breaking space If Len(Trim(Replace(rng.Item(ix).Formula, Chr(160), ""))) _ = 0 Then rng.Item(ix).Delete (xlUp) Next done: Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Replace became available in Excel 2000 VBA, in prior versions of Excel use the worksheet function, same first three operands. Replace(expression, find, replace[, start[, count[, compare]]]) Application.WorksheetFunction.SUBSTITUTE(text,old_text,new_text,ins tance_num) The use of Intersect speeds up the macro by reducing the range checked to within the used range, making selection of entire columns feasible. More information on use of Intersect and some other aspects of the above code can be seen in the notations for the Proper macro. Insertions and deletions should always be done from the bottom so that all cells are checked. Using the item count starts from the lower right cell in the range and goes backwards right to left then rightmost cell in range on row above. The HTML non-breaking-space (&nbsp;) character will be treated for removal as if a space. Included in test because a lot of pasting from HTML pages is now being done. Cells that are empty or contain only spaces will be deleted. Warning: Greenbar shading of alternate rows will be broken, unless you you use Conditional Formatting.

Example
Selecting the Range A1:C7 and then running the above macro. Note that the yellow formatted cells that are deleted will be lost and cell move up to replace the deleted cells. The grey in the AFTER is used to help differentiate the original selection range, but only the yellow cells retain the original formatting. BEFORE A 1 A1 2 3 4 5 6 A6 7 A7 8 ZZZ B B1 B2 B4 B6 B7 ZZZ D D1 D2 D3 C4 D4 D5 C6 D6 C7 D7 ZZZ D8 C C1 C2 A A1 A6 A7 ZZZ xx AFTER B B1 B2 B4 B6 B7 ZZZ C C1 C2 C4 C6 C7 ZZZ xx xx D D1 D2 D3 D4 D5 D6 D7 D8

1 2 3 4 5 6 7 8 A12

9 xx xx D9 9 xx D9 10 xx D10 10 B12 C12 D10 11 xx D11 11 D11 12 A12 B12 C12 D12 12 D12 The test data used in the above illustration was generated using MarkCells then some cells were deleted and some cells include only spaces before running DelCellsUp. It doesn't matter whether the cells contained only spaces or were empty, DelCellsUp eliminates both.

Some thoughts for future


Some Coding that was used during creation of above or may get used later. I will be wanting to create a similar macro that restricts operations within the range -- in other words one that does not move cells up from below range. Also another macro to move cells left instead of up.
'Set lastcell = cells.SpecialCells(xlLastCell) 'maxrow = lastcell.Row 'will want to limit scope '-mark selection range in pale yellow 'Selection.Interior.Color = RGB(255, 255, 192) '-mark empty cells xlblanks that would be deleted with magenta 'Selection.SpecialCells(xlBlanks).Interior.Color = RGB(255, 0, 255) 'v = Selection.Item(ir, ic).Value 'If Len(v) = 0 Then Selection.Item(ir, ic).Delete

Delete only the Empty cells (#emptycells)


version for XL97 and up
In Excel a Blank cell is a cell that has never had anything entered into it. A cell that has it's contents deleted with the Del key also qualifies. A cell that contains spaces or an unprinted zero do not qualify as a blank cell. ISBLANK() is the equivalent worksheet test for VBA xlBlanks in XL95 or xlCellTypeBlanks in XL97. Someone is always going to come up with something better. This one liner was posted by Matt Neuburg, Aug 3, 1998 in excel.programming. It does not run on my XL95, it is for XL97 and above. (see version for XL95 below) Sub DelEmpty() 'Matt Neuburg, PhD http://www.tidbits.com/matt Aug 3, 1998 Selection.SpecialCells(xlCellTypeBlanks).Delete (xlShiftUp) End Sub Actually there is a problem if you select more than 8,192 non-contiguous cells with your macro (MS KB 832293). Similar code to delete entire rows when Column A is empty with the same consideration for MS KB 832293.
Sub del_COLA_empty()

'D McRitchie http://www.mvps.org/dmcritchie/excel/delempty.htm 2004-01-10 'based on Matt Neuburg, PhD http://www.tidbits.com/matt Aug 3, 1998 'Loop required due to MS KB http://support.microsoft.com/?kbid=832293 Dim i As Long Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual i = Cells.SpecialCells(xlCellTypeLastCell).Row For i = i To 1 Step -8000 On Error Resume Next 'in case there are no blanks Range(Cells(Application.WorksheetFunction.Max(1, i - 7999), 1), _ Cells(Application.WorksheetFunction.Max(i, 1), 1)). _ SpecialCells(xlCellTypeBlanks).EntireRow.Delete On Error GoTo 0 Next i Application.Calculation = xlCalculationAutomatic 'pre XL97 xlManual Application.ScreenUpdating = True ActiveSheet.UsedRange 'Resets UsedRange for Excel 97 End Sub

Generate test data (#testdata) for testing the above in a worst case scenario where every other row makes for most discontiguous cells possible.
A1: B1: c1: A2: A3: A4: A1 1 =IF(ISTEXT(A1),A1&"",B1+0) (empty) A3 (empty)

Select B1:B20000, Edit, Fill, Series Select A1:A4, double click on fill handle Select C1, double click on fill handle (left will be used for extent, since no cells on right)

Coloring of cells based on CellType, also serves as a Demonstration of Failure in SpecialCells (#failure / #coloring) When you create a Microsoft Visual Basic for Applications (VBA) macro that selects multiple non-contiguous ranges in a Microsoft Excel workbook that uses a VBA expression that is similar to the following, actions that were only supposed to occur with blank cells occur to every cell that has been selected on the worksheet:expression.SpecialCells(xlCellTypeBlanks)expression This behavior in SpecialCells occurs if you select more than 8,192 noncontiguous cells with your macro. Excel only supports a maximum of 8,192 non-contiguous cells through VBA macros. -- Thanks to Ron de Bruin for finding this problem and bringing attention to the MS KB article. The following table consists of test data generated above for a worst case scenario. the tables are identically created but the first table is reduced to 20 rows, the second table consists of 20000 rows.

The table below shows coloring added by the subroutine -- Column A has text constants or empty cells, Column B has number constants, Column C has formulas showing text constants or number constants.
Sub SpecialCells_Coloring() 'demonstrates failure if more than 8192 cells selected by specialcells 'see MS KB http://support.microsoft.com/?kbid=832293 Dim rng As Range, cnt(5) As Long Set rng = ActiveSheet.UsedRange Cells.Interior.ColorIndex = xlNone On Error Resume Next rng.SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 36 rng.SpecialCells(xlCellTypeConstants, xlTextValues).Interior.ColorIndex = 37 rng.SpecialCells(xlCellTypeConstants, xlNumbers).Interior.ColorIndex = 38 rng.SpecialCells(xlCellTypeFormulas, xlTextValues).Interior.ColorIndex = 39 rng.SpecialCells(xlCellTypeFormulas, xlNumbers).Interior.ColorIndex = 40 cnt(1) = rng.SpecialCells(xlCellTypeBlanks).Count cnt(2) = rng.SpecialCells(xlCellTypeConstants, xlTextValues).Count cnt(3) = rng.SpecialCells(xlCellTypeConstants, xlNumbers).Count cnt(4) = rng.SpecialCells(xlCellTypeFormulas, xlTextValues).Count cnt(5) = rng.SpecialCells(xlCellTypeFormulas, xlNumbers).Count On Error GoTo 0 If cnt(1) + cnt(2) + cnt(3) + cnt(4) + cnt(5) <> rng.Count Then MsgBox "Results probably in error, including these numbers, " & _ "see MS KB http://support.microsoft.com/?kbid=832293 " _ & Chr(10) & "Blanks = " & cnt(1) _ & Chr(10) & "Text Constants = " & cnt(2) _ & Chr(10) & "Number Constants = " & cnt(3) _ & Chr(10) & "Text from Formulas = " & cnt(4) _ & Chr(10) & "Numbers from Formulas = " & cnt(5) _ & Chr(10) & "actual cells in used area = " & rng.Count End If End Sub

A 1 a1 2 3 a3 4 5 a5 6 7 a7 8 9 a9 10 11 a11 12 13 a13 14 15 a15 16 17 a17 18 19 a19 20

B 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

C a1 2 a3 4 a5 6 a7 8 a9 10 a11 12 a13 14 a15 16 a17 18 a19 20

A 1 a1 2 3 a3 4 5 a5 6 7 a7 8 9 a9 10 11 a11 12 13 a13 14 15 a15 16 17 a17 18 19 a19 20

B 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

C a1 2 a3 4 a5 6 a7 8 a9 10 a11 12 a13 14 a15 16 a17 18 a19 20

Version for XL95


Compatibility between XL95 and XL97 is certain demonstrated in the differences betwee these two macros.

xlblanks is used in XL95, but in XL97 it is xlCellTypeBlanks xlUp is used in XL95, but in XL97 it is xlShiftUp

The code of Matt Newburg above that is so short requires more coding in XL95, following is the equivalent XL95. It is the same as code I created for DelCellsUp, but only eliminates xlBlanks cells. Sub DelEmpty() 'David McRitchie 08/08/1998 ' http://www.mvps.org/dmcritchie/excel/excel.htm

'Delete Empty Cells and move cells up from below even 'if not in range. Will process ranges of one or more columns Application.ScreenUpdating = False For ix = Selection.Count To 1 Step -1 If Selection.Item(ix) = x1Blanks Then _ Selection.Item(ix).Delete (xlUp) Next ix Application.ScreenUpdating = True End Sub

Removing Empty Cells and Shifting Left


Not for Excel 95. Valid only for Excel 97 and up the process multiple selections. Based on recording a macro. 1. 2. 3. select all cells (ctrl+a, or grey button left of column letters) Edit, GoTo, [Special], blanks Edit, Delete

Sub DelEmptyMoveLeft() Cells.Select Selection.SpecialCells(xlCellTypeBlanks).Select Selection.Delete Shift:=xlToLeft End Sub

You can reduce the above to: (note similarity to Matt Newburg's code)
u Sub DelEmptyMoveLeft() Cells.SpecialCells(xlCellTypeBlanks).Delete Shift:=xlToLeft End Sub

Suppose you only want to remove blank cells in column 16 through rightmost column. Columns("P:IV").Select for selection, but that would be dependent on 256 columns See coding below not dependent on 256 columns.
Sub DelEmptyMoveLeft_StartColumnP() Range(Cells(1, 16), Cells(1, Columns.Count)).EntireColumn.Select Selection.SpecialCells(xlCellTypeBlanks).Select Selection.Delete Shift:=xlToLeft End Sub

Deleting Rows (#rows)


Delete ALL rows with blank cells in a particular Column (#deleterows)

In a posting 1998-05-17 to programming newsgroup, Dana DeLouis points out that SpecialCells frequently provides a quick method of eliminating loops, and because SpecialCells is limited to the UsedRange it will not be wasting time looping through the end of a worksheet. His Example:
On Error Resume Next ' In case there are no blanks Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete ActiveSheet.UsedRange 'Resets UsedRange for Excel 97

To also delete rows where there is a zero in column A, you can change them to Blank and eliminate the rows as above, all without using a loop. -- Myrna Larson (example) Columns("A:A").Replace 0, "", xlWhole The above does not work in XL95 and earlier versions. You get an error about not being able to do this with a multiple selection. -- Myrna Larson An equivalent Worksheet solution provided by Jim Rech 2001-02-28 1. 2. 3. Select the range in question, A1:A10. F5, Special, Blanks, OK. Ctrl-Minus and pick Shift Cells Up or Entire Row.

Delete ALL rows that are not numeric in Column E (#DeleteNonNumeric_ColE)


Because these are single instructions in VBA deleting rows all at once, there is no need for loops nor to turn off calculation or to turn off screen updating. The second parameters of SpecialCells can be added together; unfortunately, you must use separate instructions for Formulas and for Constants. There are no titles in Row 1 in this example, which makes for this simple example. Sub DeleteNonNumeric_ColE() On Error Resume Next Range("e:e").SpecialCells(xlBlanks, _ xlTextValues).EntireRow.Delete Range("e:e").SpecialCells(xlConstants, _ xlTextValues).EntireRow.Delete Range("e:e").SpecialCells(xlFormulas, _ xlTextValues + xlErrors + xlLogical).EntireRow.Delete On Error GoTo 0 End Sub Delete ALL rows that are not numeric in Column E (#DeleteNonNumeric_ColE2DN) But we can make this leave row 1 alone by including rows("2:" & rows.count)

Sub DeleteNonNumeric_ColE2DN() On Error Resume Next Intersect(Rows("2:" & Rows.Count), Range("e:e").SpecialCells(xlBlanks, _ xlTextValues)).EntireRow.Delete Intersect(Rows("2:" & Rows.Count), Range("e:e").SpecialCells(xlConstants, _ xlTextValues)).EntireRow.Delete Intersect(Rows("2:" & Rows.Count), Range("e:e").SpecialCells(xlFormulas, _ xlTextValues + xlErrors + xlLogical)).EntireRow.Delete On Error GoTo 0 End Sub

Delete ALL rows that have cell in Column A that looks blank

(#DeleteRowsThatLookEmptyinColA)

Keeping in mind that cells that have spaces or formulas are never blank but could appear to be to the casual observer, the following will TRIM the value of the cell and check for a length of 0. Since data could come from HTML a non-breaking space (&nbsp;) or CHR(160) will be treated as a space which is CHR(32). The TrimALL macro is a another macro that takes the &nbsp; character into consideration when trimming. Sub DeleteRowsThatLookEmptyinColA() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim Rng As Range, ix As Long Set Rng = Intersect(Range("A:A"), ActiveSheet.UsedRange) For ix = Rng.Count To 1 Step -1 If Trim(Replace(Rng.Item(ix).Text, Chr(160), Chr(32))) = "" Then Rng.Item(ix).EntireRow.Delete End If Next done: Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub See earlier note concerning REPLACE, which became available in Excel 2K VBA. Modified to process all sheets (#Allsheets_Delete_Rows_Empty_in_column_A For additional examples in processing all sheets see sheets.htm and collections.htm Public Sub Allsheets_Delete_Rows_Empty_in_column_A() Application.Calculation = xlManual 'xl97 up use xlCalculationManual Application.ScreenUpdating = False Dim Rng As Range, ix As Long Dim csht As Long For csht = 1 To ActiveWorkbook.Sheets.Count 'worksheet or sheets

Set Rng = Intersect(Worksheets(csht).Range("A:A"), _ Worksheets(csht).UsedRange) For ix = Rng.Count To 1 Step -1 If Trim(Replace(Rng.Item(ix).Text, _ Chr(160), Chr(32))) = "" Then Rng.Item(ix).EntireRow.Delete End If Next done: Next csht Application.ScreenUpdating = True Application.Calculation = xlAutomatic 'xl97 up use xlCalculationAutomatic End Sub

Delete ALL rows that are Entirely Blank (#RemoveEmptyRows)


Delete All Rows that are completely empty
Sub RemoveEmptyRows() Application.ScreenUpdating = False 'xlManual below in Xl95 Application.Calculation = xlCalculationManual Dim rw As Long, iCol As Long For rw = ActiveSheet.UsedRange.Rows.Count To 1 Step -1 If Application.CountA(Rows(rw).EntireRow) = 0 Then _ Rows(rw).Delete Next Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True 'xlAutomatic above in xl95 End Sub '----- same thing below --Sub DelEmptyRows() Dim chkRange As Range, i As Long, iLimit As Long Set chkRange = Columns("a").SpecialCells(xlCellTypeBlanks) iLimit = chkRange.Count If iLimit = 0 Then Exit Sub Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual For i = iLimit To 1 Step -1 If Application.CountA(chkRange.Item(i).EntireRow) = 0 _ Then chkRange.Item(i).EntireRow.Delete Next i Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True iLimit = ActiveSheet.UsedRange.Rows.Count 'attempt to fix lastcell ActiveWorkbook.Save End Sub

Cells that look blank may contain spaces and are therefore not blank (ISBLANK) in Excel's unfortunate choice of wording. Cells with formulas will never test as ISBLANK. (ISBLANK in MS Excel terms really means NULL never used or at least no content).

Related: To make the activecell become the lastcell for the sheet, deleting all columns and rows after that cell see MakeLastCell. Also of interest might be Insert a Row using a Macro to maintain formulas.

Delete rows with "N" in Column 31 (#Delete_N_MarkedRows)


Sub Delete_N_MarkedRows() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim lastrow As Long, r As Long lastrow = ActiveSheet.UsedRange.Rows.Count For r = lastrow To 1 Step -1 If UCase(Cells(r, 31).Value) = "N" Then Rows(r).Delete Next r Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Delete rows with specific value in Column A and on same row specific value in column B (#Delete_rows_based_on_ColA_ColB)
Sub Delete_rows_based_on_ColA_ColB() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range, rng As Range, i As Long Set rng = Columns("A").SpecialCells(xlConstants, xlTextValues) For i = rng.Count To 1 Step -1 If LCase(rng(i).Value) = "standard" _ And LCase(rng(i).Offset(0, 1).Value) = "card" _ Then rng(i).EntireRow.Delete Next i Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Delete rows with specific values, new twist, make a union of ranges for delete (#Delete_Rows) An interesting twist by paul ??, 2003-01-10, invoves creating a Union of ranges containing a specific value, and then deleting all of the rows at one time in one instruction.
Sub Delete_Rows() ' This macro deletes all rows on the active worksheet ' that have 1034, 1035, 1037 column E. Dim rng As Range, cell As Range, del As Range Set rng = Intersect(Range("E:E"), ActiveSheet.UsedRange) For Each cell In rng If (cell.Value) = "1034" _ Or (cell.Value) = "1035" _ Or (cell.Value) = "1037" Then If del Is Nothing Then Set del = cell Else: Set del = Union(del, cell) End If

End If Next cell On Error Resume Next del.EntireRow.Delete End Sub

Massive Delete Rows / Insert Rows for those selected in Column A (#A_Selected_Delete_Rows) Thought I had something new here but almost same as those above. --David
Sub A_Selected_Delete_Rows() Intersect(Selection, Range("A:A"), _ ActiveSheet.UsedRange).EntireRow.Delete End Sub Sub A_Selected_Insert_Rows() Intersect(Selection, Range("A:A"), _ ActiveSheet.UsedRange).EntireRow.Insert End Sub

Delete ALL rows above the active cell (#MassDeleteAboveActive)


Sub MassDeleteAboveActive() Rows("1:" & (ActiveCell.Row - 1)).Delete End Sub 'posted to programming 2000-02-19 D.McRitchie

Delete ALL rows from A1 to find cell value in Column A (#DelRows1toFind)


Sub DelRows1toFind() Dim rng As Range 'Tom Ogilvy, 2003-02-11, programming Set rng = Columns(1).Find("feng", Cells(1, 1)) If Not rng Is Nothing Then Range(Cells(1, 1), rng).EntireRow.Delete End If End Sub

More deleting rows (#DelRowNoAst)


This will delete rows for which a cell in the selection area is blank.
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

The following will process only cells with Text constants, when looking to delete non asterisk rows.
Sub DelRowNoAst() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim ix As Integer If Selection.Columns.Count <> 1 Then

'in XL97

MsgBox "Only select one column to retain rows with asterisks" Exit Sub End If Selection.SpecialCells(xlBlanks).EntireRow.Delete Selection.SpecialCells(xlCellTypeConstants).Select For ix = Selection.Count To 1 Step -1 If Selection.Item(ix) <> "*" Then _ Selection.Item(ix).EntireRow.Delete Next ix Application.Calculation = xlCalculationAutomatic 'in XL97 Application.ScreenUpdating = True End Sub

xlBlanks for XL95, xlCellTypeBlanks above XL95 xlManual or XlAutomatic for XL95

Delete all rows where a cell contains text "ANN" in any cell in range (#find)
This code will delete all rows where a cell contains the text "ANN" anywhere within such cells. e.g. ANNxxx xxANNxx xxANN From a posting by Patrick Molloy, programming, 2002-11-26 Sub Find_ANN() Dim rng As Range Dim what As String what = "ANN" Do Set rng = ActiveSheet.UsedRange.Find(what) If rng Is Nothing Then Exit Do Else Rows(rng.Row).Delete End If Loop End Sub Note that FIND in VBA is similar to the FIND shortcut (Ctrl+F); whereas InStr in VBA is similar to the FIND function in Excel. (See strings.htm if that interestes you.

Delete ALL rows where cell value is equal to x in selected columns (#deleteequal)
(see previous topic for what is probably better) The following is based in MS KB article Q213544 which I believe was poorly written. Actually it's purpose was to show that bad code did not work consistently in different versions, but the recommended and alternate codings were in my opinion not of good design either.

Forget the recommended way in Q159915 and Q213544 The Alternate one thrown in at the end of the articles which starts from the bottom and deletes rows without stepping over it's own toes is better in that it uses
For i = rng.Rows.Count To 1 Step -1

but still leaves some some fairly poor coding. FWIW adjusting a counter used within a loop is not legal in all languages anyway and in others destroys optimization. Adjusting the variable within the FOR ... Next loop is harder to follow the coding and apparently is not consistent between Excel versions. My opinion is that all of them are bad examples because they used hard coded ranges. Use of rows should use Long instead of Integer at least in XL97 and up where rows can go up to 65,536 way beyond 16,384 rows in XL95. Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767 Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647. Have included turning off calculation and screen updating to make it run faster. In XL95 use xlManual and xlAuto instead. Excel constants begin with XL in lowercase just so you won't confuse with other letters or numbers.
Sub DeleteCells4() 'modified from ' http://support.microsoft.com/default.aspx?scid=kb;en-us;Q213544 'see http://www.mvps.org/dmcritchie/excel/delempty.htm Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim rng As Range, i As Long '// modified 'Set the range to evaluate to rng. // modified Set rng = Intersect(Selection, ActiveSheet.UsedRange) If rng Is Nothing Then MsgBox "nothing in Intersected range to be checked" GoTo done End If 'Loop backwards through the rows 'in the range that you want to evaluate. '--- For i = rng.Rows.Count To 1 Step -1 // modified For i = rng.Count To 1 Step -1 'If cell i in the range contains an "x", delete the entire row. If rng.Cells(i).Value = "x" Then rng.Cells(i).EntireRow.Delete Next done: Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Possible change -- restrict to column A only:


Set rng = Intersect(Selection, Range("A:A"), ActiveSheet.UsedRange) If rng Is Nothing Then MsgBox "nothing in Intersected range to be checked," _ & Chr(10) & "there is an internal range(""a:a"")" GoTo done End If

Possible change -- check for any of several values, and possibly use TRIM
If rng.cells(i).value = "x" Or TRIM(rng.cells(i).value) = "delete" then rng.Cells(i).EntireRow.Delete End If

Clear Content of adjacent cells where cell in Column G appears blank (#MoAli1)
Sub MoAli1() 'Clear out values in Gx:Mx when value in col G appears empty 'see http://www.mvps.org/dmcritchie/excel/delempty.htm 2000/07/29 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range For Each cell In Application.Intersect(ActiveSheet.Range("g:g"), _ ActiveSheet.UsedRange) If Trim(cell.Value) = "" Then ActiveSheet.Range(cell, cell.Offset(0, 6)).ClearContents End If Next Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Note: Test for ISEMPTY(cell.value) not needed with TRIM(cell.value) but might be useful for modified code. Certain aspects of code can be found in examples in slowresp.htm, turning calculation off for speed; proper.htm, see comments at top, including use of INTERSECT; join.htm, general information, include MarkCells used to create test data.

Delete All Even Numbered Rows (#DelEvenRows)


Perhaps this could be done without a loop but here is one way.
Sub DelEvenRows() 'David McRitchie 2002-03-11 misc 'Delete Even numbered rows from the bottom Application.ScreenUpdating = False Dim ix As Long For ix = Cells.SpecialCells(xlLastCell).Row To 2 Step -1 If ix Mod 2 = 0 Then Rows(ix).Delete Next ix Application.ScreenUpdating = True

End Sub

Delete Entire Rows for active cell or for Selection (#DelSelection_Rows)


Sub DelActiveCell_Row() ActiveCell.EntireRow.Delete End Sub Sub DelSelection_Rows() 'in Excel 2000 multiple selections okay 'if they don't overlap Selection.EntireRow.Delete End Sub

Delete x number rows above row 25


rows(25).Offset(-x).Resize(x).delete

Related Items (#related)


How to install/use a macro can be found on my formula page. Color Palette -- 56 Excel Colors, Attempts to equate Excel ColorIndex values to RGB colors used in HTML. Includes formatting colors: [BLACK] [BLUE] [CYAN] [GREEN] [MAGENTA] [RED] [WHITE] [YELLOW] [COLOR1]..[Color56] and other color information. Color Sorting (on another page). Fill in the Empty Cells, this macro will fill in empty cells with the content of the cell above it, providing the cell above is also within the selection range. Insert ROW using a Macro, the macro described will insert row(s) below a selected row or cell. The advantage of using a macro is that the formulas will be copied, but not the data; providing a more reliable method of inserting lines than simply inserting a row and then dragging a row with formulas and data into an inserted empty row. Reset Last Cell Used Attempts to provide additional information concerning eliminating unused rows at end and unused columns to right of sheet beyond what can be seen in Q134617. Back on my web page, MakeLastCell makes the activecell become the lastcell by deleting all rows and columns that appear after the active cell, and QueryLastCells lists sheets in workbook using an excessive number of cells, similar to information provided in BuildTOC on another page.

Related Information in Postings

(#postings)

Remove leading, trailing, and duplicate hyphens from selected cells that have constants (ignores formulas). Option Explicit Sub REMXHYPS() 'David McRitchie 2000-02-27 excel.programming

'hyphen removals of dups, prefixed, suffixed, and trim results Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'pre XL97 xlManual Dim newstr As String Dim oldstr As String Dim lst As String Dim ix As Integer Dim x As String Dim cell As Range For Each cell In Selection.SpecialCells(xlCellTypeConstants, 2) 'above limits to constants which are TEXT If InStr(1, cell.Value, "-") Then lst = "-" newstr = "" oldstr = Trim(cell.Value) For ix = 1 To Len(oldstr) x = Mid(oldstr, ix, 1) If x = "-" Then If lst <> "-" Then newstr = newstr & x Else newstr = newstr & x End If lst = Mid(oldstr, ix, 1) Next If Right(newstr, 1) = "-" Then newstr = Left(newstr, Len(newstr) - 1) cell.Value = Trim(newstr) End If Next Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic Application.ScreenUpdating = True End Sub HTH, David McRitchie, Microsoft MVP - Excel My Excel Pages: http://members.aol.com/dmcritc hie/excel/excel.htm tim williams <[email protected]> wrote in message news:[email protected]... > > > > > > Function formatMe(stuff As String) stuff = Trim(stuff) 'remove trailing -'s Do While Right(stuff, 1) = "-" stuff = Left(stuff, Len(stuff) - 1) Loop

> strTemp = "" > bFlag = False > For n = 1 To Len(stuff) > If Mid(stuff, n, 1) = "-" And bFlag = False Then > strTemp = strTemp & Mid(stuff, n, 1) > bFlag = True > ElseIf Mid(stuff, n, 1) <> "-" Then > strTemp = strTemp & Mid(stuff, n, 1) > bFlag = False > End If > Next n > formatMe = strTemp > End Function > > > > > Mike Van Sydenborgh <[email protected]> wrote in message news:[email protected]... > A file that I import into Excel, leaves hypens around the data I'm > interested in. > Some examples are:

> > DCK-43V--> > FS--4824--G3--> > SWS---7224--S > > I want one hyphen between letters like SWS-7224-S and the hypens beyond > > letters to be removed like this: FS-4824-G3 > > The final product should appear as: DCK-43V, FS-4824-G3, > > SWS-7224-S

Delete duplicates in column, and values duplicating values found on original sheet in the designated column, Tom Ogilvy, 2002-12-20, Re: Duplicate Rows for 5 Sheets. Remove content of cells with constants that look empty, but are not, David McRitchie, 2003-07-23, worksheet.functions -- not deleting the cells which would cause cells to move up, but only remove the constants so that they are in fact EMPTY.

Related Information on Other Sites (#offsite)


DeleteBlankRows() on Chip Pearson's pages. If cell in the selected range (one column) is empty (ISBLANK) then the entire row will be deleted. Warning no check is made for lastcell on sheet so select your range carefully. Conditional Row Delete, John Walkenbach, add-in requires Excel 97 or higher (73K self-extracting download).

Microsoft Knowledge Data Base (MS KB)

(the following is just a place holder and will be changed) Q107564 XL: Not All Worksheet Functions Supported as Application (in VBA) Run-Time Error '438': Object doesn't support this property or method

This page was introduced on July 17, 1998.

(last update: Thu, 19 May 2005 17:54:53 GMT)

[My Excel Pages -- home] [INDEX to my site and the off-site pages I reference] [Site Search -- Excel] [Go Back] [Return to TOP]
Please send your comments concerning this web page to: David McRitchie send email comments

Copyright 1997 - 2004, F. David McRitchie, All Rights Reserved


Sub getShapeProc() 'List of buttons/shapes ON THE worksheets 'based on Shawn Foley, programming group, 1999-09-10 '-- http://groups.google.com/groups? as_umsgid=7rbk95%24b44%241%40nntp8.atl.mindspring.net Dim Wks As Worksheet Dim shp As Shape Dim nRow As Long Sheets.Add 'Don't destroy the active sheet Cells.Clear '-- added due to on Error Cells(1, 1) = "Worksheet" Cells(1, 2) = "Shape" Cells(1, 3) = "Type" Cells(1, 4) = "OnAction" Cells(1, 5) = "Hyperlink" Cells(1, 6) = "TopLeft" Cells(1, 7) = "BotRight" Cells(1, 8) = "Height" Cells(1, 9) = "Width" Cells(1, 10) = "Autoshape" Cells(1, 10).AddComment "Autoshape Type" Cells(1, 11) = "Form" Cells(1, 11).AddComment "Form Control Type" nRow = 1 On Error Resume Next 'hyperlinks, topLeftCell, BottomRightCell For Each Wks In ActiveWorkbook.Worksheets For Each shp In Wks.Shapes nRow = nRow + 1 Cells(nRow, 1) = "'" & Wks.Name 'i.e. Worksheet 1999-01-10 Cells(nRow, 2) = shp.Name Cells(nRow, 3) = shp.Type Cells(nRow, 4) = shp.OnAction Cells(nRow, 5) = shp.Hyperlink.Address 'additional information Cells(nRow, 6) = shp.TopLeftCell.Address(0, 0) Cells(nRow, 7) = shp.BottomRightCell.Address(0, 0) Cells(nRow, 8) = shp.Height Cells(nRow, 9) = shp.Width Cells(nRow, 10) = shp.AutoShapeType Cells(nRow, 11) = shp.FormControlType 'i.e. autofilter button is 2

'Debug.Print wks.Name & Chr(9) & shp.Name & Chr(9) & shp.OnAction '------no/no shp.Delete Next shp 'If wks.Name = "Abuse" Then GoTo done 'testing D.McRitchie Next Wks done: nRow = nRow + 0 End Sub ' Dave Peterson showed us that you don't need a loop at all ' just two lines of code on the inside. (misc 2001-11-12) Sub delShapesOnSht() 'Dave Peterson, misc 2001-11-12, no loop required If ActiveSheet.Shapes.Count = 0 Then MsgBox "No Shapes on page for deletion" Exit Sub End If ActiveSheet.Shapes.SelectAll '*** warning DELETE all Shapes Selection.Delete End Sub ' Dave Peterson provided another example in programming 2001-11-13 ' to delete shapes with upper left corner within a selection range. ' -- had -- ActiveSheet.Range("a37:o50")) Is Nothing Then Sub delShapesSel() 'Delete shapes within selection range, ' Dave Peterson, programming, 2001-11-13 Dim myshape As Shape For Each myshape In ActiveSheet.Shapes If Intersect(myshape.TopLeftCell, _ Selection) Is Nothing Then 'do nothing Else myshape.Delete End If Next myshape End Sub

Missed the specific range in the above, it would be better to use Selection. instead of ActivesSheet.Range("a37:o50") -- one person used BottomRightCell instead of TopLeftCell due to the way that multiple shapes hit one cell. Modify to suit your needs. You can manually select all objects on a sheet regardless of what cells are selected with Edit, GoTo (Ctrl+G), Special, Objects.
Sub selShapesOnSht() Dim shp As Shape For Each shp In ActiveWorkbook.ActiveSheet.Shapes ans = MsgBox("DELETE Shape" & Chr(10) & shp.Name & " " _ & shp.TopLeftCell.Address & Chr(10) & " -- " _ & shp.AlternativeText, vbYesNoCancel + vbDefaultButton2) If ans = 2 Then shp.Select 'Select shape and exit Exit Sub End If If ans = 6 Then shp.Delete 'Delete the shape Next shp End Sub Sub CheckShape() 'Find names of objects on a sheet -- Tom Ogilvy 01Nov199

'untested (dmcr) has a range("myzone") Dim varArr() Dim shpRange As ShapeRange ReDim varArr(1 To 1) i=0 For Each shp In Worksheets("sheet1").Shapes If shp.Type = msoFreeform Then If Not Intersect(Range("MyZone"), _ shp.TopLeftCell) Is Nothing Then i=i+1 ReDim Preserve varArr(1 To i) varArr(i) = shp.Name End If End If Next Set shpRange = ActiveSheet.Shapes.Range(varArr) Debug.Print shpRange.Count For Each shp In shpRange Debug.Print shp.Name, shp.TopLeftCell.Address Next shpRange.Select End Sub Code for Particular Shapes: If sp.AutoShapeType = msoShapeRectangle Then sp.Delete If sp.AutoShapeType = msoShapeTriangle Then sp.Delete Code to find out who called a macro attached to a shape: msgbox "This macro was called by: " & _ ActiveSheet.Shapes(Application.Caller).Name 'returns string

Find Shape at a Location (#find)


Dave Peterson, programming, 2002-06-16
Sub testme3() Dim myCell As Range, myShape As Shape Set myCell = Range("A1") For Each myShape In ActiveSheet.Shapes If Intersect(myShape.TopLeftCell, myCell) Is Nothing Then 'do nothing Else MsgBox myShape.Name Exit For End If Next myShape End Sub

Create an Anchored Shape (#anchor)


Creating a shape anchored to the four borders of a cell. Even though the shape is anchored to the four borders, you can manually move the image and change it's shape, but the image remains anchored to the four original points (cell's top, left, width, height)and will distort according to their movement of those borders. (see code on left below) A shape's default .Placement property value is xlMoveAndSize. Change it to xlFreeFloating if desired -- then the the image is anchored to the upper left corner of the

spreadsheet and removal of columns does not affect it's position. (see code on right below) JE McGimpsey, public.excel, 2004-08-30.
With Range("J4") ActiveSheet.Shapes.AddShape _ Type:=msoShapeSmileyFac e, _ Left:=.Left, _ Top:=.Top, _ Width:=.Width, _ Height:=.Height End With With Range("K10") With ActiveSheet.Shapes.AddShape( _ Type:=msoShapeSmileyFace ,_ Top:=.Top, Left:=.Left, _ Width:=.Width, _ Height:=.Height) .Placement = xlFreeFloating End With End With

Name of shape(s) in a Selection (#name)


Curious that you can have multiple shapes selected (Shift+click on shape), but for a single shape you cannot get a selection.count. Incomplete check the newsgroup thread for later information. Ideally this should indicate exactly which if any shape was actually selected. Single selection Chart or TextBox currently are not properly represented, nor when there are actually no shapes selected like when a single cell is selected.
Sub IDthisShape() 'Identify selected shape, David McRitchie, programming, 2002-12-20 ' http://www.mvps.org/dmcritchie/excel/shapes.htm ' http://google.com/groups?threadm=uV1T2%23FqCHA.2484@TK2MSFTNGP12 Dim str As String, i As Long, cnt As Long cnt = 0 On Error Resume Next cnt = Selection.Count cnt = Selection.ShapeRange.Count '-- err if none selected str = "There are " & ActiveSheet.Shapes.Count _ & " shapes on this worksheet" _ & Chr(10) & "of which " & cnt _ & IIf(cnt = 1, " was selected", " were selected") _ & Chr(10) & Chr(10) If cnt = 0 Then '-- can at least report a single chart but not a single textboxl str = str & "Actually, Selected shape is: " & Selection.Name MsgBox str Exit Sub End If For i = 1 To Selection.ShapeRange.Count MsgBox str & i & " of " & Selection.ShapeRange.Count _ & " in selection. The selected shape is " _ & Chr(10) & " " & Selection.ShapeRange.Item(i).Name Next i End Sub

Extract and Place Hyperlink from Shape into cell to the right (#ExtractLinkToRightOfShapes)
Sub ExtractLinkToRightOfShapes() 'Extract hyperlink and place to right of cells with shapes 'Dick Kusleika, 2003-03-26 in excel.links, modified from ' http://google.com/groups?threadm=efcLbz%238CHA.2820%40TK2MSFTNGP11.phx.gbl Dim shp As Shape

For Each shp In ActiveSheet.Shapes On Error Resume Next shp.BottomRightCell.Offset(0, 1).Value = "'--" shp.BottomRightCell.Offset(0, 1).Value = shp.Hyperlink.Address On Error GoTo 0 Next shp End Sub

Resizing Shapes (#resize)


Sizes are in points so 4 * 72 is 4 inches. The following is a test and example you can add msgbox code to view results at various points if you wish to see something particular.
Sub Macro19() Dim wfactor As Double Dim shp As Shape 'Delete all shapes to begin test For Each shp In ActiveWorkbook.ActiveSheet.Shapes shp.Delete '****** warning DELETE all Shapes found Next shp 'Create some shapes ActiveSheet.Shapes.AddShape(msoShapeRectangle, _ 36#, 151.5, 202.5, 125.25).Select ActiveSheet.Shapes.AddShape(msoShapeOval, _ 544.5, 154.5, 57#, 41.25).Select 'Resize each shape to 4 inches height and width For Each shp In ActiveWorkbook.ActiveSheet.Shapes shp.Height = 4 * 72 shp.Width = 4 * 72 Next shp 'Rescale each shape to 2 inches width and scale height For Each shp In ActiveWorkbook.ActiveSheet.Shapes wfactor = 2 * 72 / shp.Width shp.Height = shp.Height * wfactor shp.Width = shp.Width * wfactor Next shp 'insert an image and resize width Dim PictureName As String PictureName = "C:\copiedsite\dmcritchie\icons\bl-green.gif" Range("A4").Select ActiveSheet.Pictures.Insert(Picturename).Select Selection.Width = 4 * 72 MsgBox TypeName(Selection) 'shows up as Picture End Sub

Dimensioning variables

(#dim)

Dimensioning variables for use with Options Explicit. If you have simply used Dim xyz as variant you can find out the actual type that you used with MsgBox typename(xyz) so you can replace variant by its actual type. Similarly MsgBox TypeName(Selection) can be use to tell what the selection is. [See Slow Response]

Shortcut, Assign Shortcut to a Shape (#shortcut)


You can assign a Macro Shortcut to your Shape by right-clicking on Shape and then choosing Properties. More information on shortcuts, Tool bars, and Event Macros.

Watermarks

(#watermarks)

Watermark, printing of, Robert Rosenberg. Creating a watermark in Excel with VBA. , Kenneth Ives (codetoad, 3/30/2003), with Word Art Print a Watermark on Excel Worksheet, Neil J. Rubenking in PC Mag (2005-01-05), text only article find more on Google Bob Phillips' page Debra Dalgleish shows how to use pictures in Comment boxes. (okay so it's not a watermark) Printing watermarks behind your data to identify confidential information [archive 2000-07-11 ] Intro to the above article at Visually mark sensitive worksheets with a VBA macro elementkjournals.com, Sean Kavanagh, Feb 2002 in EKJ online. How to create a watermark in Word 97 and in Word 2000 (probably much the same in Excel)

Related (#related)

Andrew's Blog, drawing shapes, squares, circles, composite assembly, 2004-05-09. Build Table of Contents, similar listings, working with Hyperlinks. Create a Table of Contents list complete with hyperlinks in XL97 and up, as well as considerations in a similar listing for XL95 without hyperlinks. Additional information for creating Excel documentation. Picture within a Comment, Debra Dalgleish Posting on covering comment triangles with colored triangles, Dave Peterson, 2003-04-25 Colors Graphics Exporter addin , Andy J. Pope, will allow you to export pictures, shapes, charts and more to image files. Link to a Chart or Shape, faked by an Event Macro, see Hyperlinks in Excel, Jon Peltier, some notes on hyperlinks including how to fake a link to a chart. Textbox on Shapes page. Slow Response, shapes are graphics and lots of them will affect graphical memory. xl2gif creates a gif or other picture file from an Excel image. Shapes like pictures, cell comment boxes, and text boxes can be hidden/unhidden with a Shortcut. Ctl+6 Alternates between hiding objects, displaying objects, and displaying placeholders for objects. Watermarks see topic above. 1,048,576 =INFO("memavail") Amount of memory available, in bytes. 3,591,860 =INFO("memused") Amount of memory being used for data. 4,640,436 =INFO("totmem") 45 =INFO("numfile") Total memory available, including memory already in use, in bytes. Number of active worksheets.

Windows (32-bit) =INFO("osversion") Current operating system version, as text.

NT 4.00 9.0 =INFO("release") Version of Microsoft Excel, as text.

Memory Leakage

(#leakage)

If you are having severe problems that can be alleviated by maintaining the Zoom at 100%, you should make sure that the have the latest print drivers for your printer The print drivers control the screen appearance. Also check the MS KB for memory leakage. Various problems have been reported against H-P printers with soft fonts, possibly after the introduction of the Euro character. Q183503 -- XL: "Not Enough System Resources" with Controls on Zoomed Sheets System Resources (as Windows calls them) are consumed by graphics images (such as charts, zoomed windows, drawing objects, fonts etc) and is limited. General Resources (memory, stack space etc). Windows operates a Paging system so that if the OS runs out of physical memory it just hijacks the disk to store the stuff it cant keep in RAM. The effect is that your spreadsheet runs more slowly, but it still runs. [Peter Beach, programming, 2002-01-14]

Memory Leakage in GDI (graphics device interface) Resources (#GDI)


Multiple Excel windows, window zoom not set at 100%, lots of graphics, colors, formats, charts, images, activex-objects. A combination of these will eat excels graphical memory, which is allocated independent of available cards, ram, speed. -- as summarized by Harald Staff. Also dont forget to close your macro windows within the VBE when you are done with them. Printers and fonts can also be involved. Windows resources is a special segment of memory that is not related to how much RAM is installed. That it is fixed by the operating system. With Windows 3.1 it was small and used up rapidly. With Windows 95/98 it was increased or at least used more efficiently so it is less of a problem With NT it is a non-issue. (Jim Rech, misc 1999-12-16, and continues) In Excel the thing to watch is graphical objects like pictures and drawing objects using up resources. Also using a lot of different fonts. MS believes that some printer drivers are at the root of some resource issues: Q165985 -- OFF: "Out of Memory" Messages When Running Microsoft Office includes more information and a list of printers. It is also possible that the latest version of the printer driver will correct the problem. The latest versions of the printer drivers can be downloaded from the following HewlettPackard Internet web site: http://www.hp.com/ Some H-P printers in

particular are identified with consuming memory and not releasing it. This can result in memory errors and it can result in dramatic slowdowns. A printer driver runs in the background and controls the display on the monitor as well as the printer. So you might try changing print drivers. Excessive use of MSGBOX about 100 times in XL2000 did not release GDI (Graphical Data Interface) resources. Check out MS KB Q102438 -- Excel: Methods for Conserving GDI Resources [dead link] for a method to check -could not get it to work failed on user library. Bypass is to use Application.MsgBox in VBA code instead of MsgBox. (See Bill Manville 1in Programming 12/04/99, GDI)

Date & Time


Location: http://www.mvps.org/dmcritchie/excel/datetime.htm Home page: http://www.mvps.org/dmcritchie/excel/excel.htm [View without Frames]
[y2k], [formatting], [intocell], [now], [datefmt], [vba], [addk], [days], [counting], [filter], [add], [thrumidnight], [military], [vbadates], [fixmmddyyyy], [totbymonth], [text2dates], [age], [daysinmonth], [firstdate], [mondaystart], [julian], [filldates], [ordinal], [lastsaved], [sheetwithdates], [weeknumber], [ws], [timediff], [subtracttime], [rndqtrhr], [fees], [core], [date123], [entryprob], [countdowny2k], [vbadate], [isdate], [MakeTrueDate], [t2cols], [adjust], [debug], [bus], [coverage], [clock], [timers], [StopWatchcontd], [vbaformat], [gwash], [timeinfo], [clocks], [dateinfo], [interesting], [related] [An example of a countdown timer for date was removed from this area that relied on Microsoft Virtual Machine, Microsoft Virtual Machine is no longer supported, you should install JAVA to run JAVA applets. ]

Something you should have changed before 2000 (#y2k)


There is enough confusion between US and UK dates without dealing with 2-digit years. Suggest you make changes such as the following so that all of your dates will display as four digit years. If you do not do this you may not be able to distinguish which part of the date is the year, the month, day; and have further difficulty knowing whether you actually have a 19xx year or a 20xx year. Excel will keep track of dates but it may not be what you see displayed or you may not be sure. Change your Regional Settings (shown with US values month/day/year) Short date: mm/dd/yyyy will show 12/28/1999 Long date: mmmm dd, yyyy

will show December 28, 1999 note this will change all of MS Office In Excel under Format --> cells --> Custom -->> mm/dd/yyyy see HELP for more information. The same letter combinations are used in Regional Settings as seen in Excel Help The short date format in Regional settings is used by Excel for the General format. The long date format in Regional settings is used by Excel for the Headings and Footings under page setup. Differences in Regional Settings may not be immediate apparent. Time in the US like =TEXT(A1,"[hh]:mm") might be =TEXT(A1,"[TT}:mm") in another language, incorrect use results in a #VALUE! error. Within double quotes such formulas may not translate in an exchange of workbooks (??). When Excel has recognized through some means that you have a date -entered as a date or assigned by a formula based on a cell that had a date, the short date form from your Windows Regional Settings will be used if your cell format is General. You can override the default formatting by specifically formatting a the column, for instance, with the date format of your choice.

Date and Time Formatting

(#formatting)

Additional information on Formatting Numbers, Dates, and Times in general can be found in the HELP topic About number format codes for dates and times. You will find that your Excel HELP is equivalent to the Excel XP pages referred to above, and you should be familiar with the HELP. I have some examples for numeric formats on my formula= page. For January: ; mmmm shows January, mmm shows Jan, mm shows 01, and m shows 1. Similar for d, dd, ddd, dddd which would show as 3, 03, Thu, Thursday for Jan 3, 2002. To format hours so that they dont roll over into days format as [h]:mm or as [hh]:mm An interesting format was pointed out by Dave Peterson where mm/dd/yyyy* dddd, places the date left justified (US format) and the day spelled out and right justified within the cell as ||11/14/2001 Wednesday||. It is typical number formatting but interesting applied to dates.

System Date/Time into a Cell or within Code (#intocell)


Placing a current date, or time, or timestamp constant that will not change later

Ctrl+; date Ctrl+: time Ctrl+: (space) Ctrl+; date with time ActiveCell.Value = Date ActiveCell.Value = Time ActiveCell.Value = Now ActiveCell.Value = Timer

(ctrl+semicolon) (ctrl+shift+colon) (ctrl+shift+semicolon)(space)(ctrl+Shift+colon) Equivalent usage in a macro for Date Equivalent usage in a macro for Time Returns current date and time in a macro Returns seconds since midnight in a macro (timing usages)

Additional Date/Time related shortcuts Ctrl+Shift+# Ctrl+Shift+@ Apply the Date format with the day, month, and year Apply the Time format with the hour and minute, and indicate A.M. or P.M.

Placing a current date or time that will update on recalculation (#now)


The use of NOW() will place the system date and time into the cell The format is dependent on your date and time settings (International settings). =NOW() date & time =Now() show date if formatted for date =Now() show time if formatted for time =int(Now()) date only, must be formatted for date =mod(Now(),1) time only, must be formatted for time See "Number format codes for dates and times" in help. example of time format: hh:mm:ss examples of date or custom date format: mm/dd/yyyy and dddd mmmm dd, yyyy

Formatting for Date and Time (#datefmt)


Formatting is done using Format --> cells --> date or custom Help --> Find --> formats --> Custom number formats --> For more information about number format codes for dates and times, click [>>]

Entering Dates into a Cell Formatted as General


Entering a month and day, or a month and year will cause the formatting to change for a General Cell. This can also produce problems if the figure entered is actually a fraction and not a date. (partial solution)
Generate s Format

Entered as:

Displays As

Actual value

Actual Date (US)

3/31

31-Mar

d-mmm

36,616.00 03/31/2000

3/32 3/31/2000 03/31/2000 3/0 3

Mar-32 mmm-yy 03/31/2000 m/d/yy 03/31/2000 m/d/yy Mar-00 mmm-yy 3 General General

11,749.00 36,616.00 36,616.00 36,586.00 3.00 -

03/01/1932 03/31/2000 03/31/2000 03/01/2000 01/03/1900

Date and Time serials


Serial for date only has no decimal places. Serial for date and time has date serial plus the time component as a fraction of a day. Serial for time is a fractional day. One hour is 1/24 day, or approximately 0.4166667 of a day as a decimal number. Formula -- =GetFormula(cell) datestamp date serial =NOW() 6/19/98 7:25 35965.31 =0.01 1/0/00 12:14 AM 0.01 =0.51 1/0/00 12:14 0.51 =10 1/10/00 0:00 10.00 =INT(NOW()) 6/19/98 0:00 35965 =MOD(NOW(),1) 1/0/00 7:25 0.309130787 =DATEVALUE(TEXT(NOW(), "mm/dd/yy")) 06/19/1998 35965.00 =DATE(NOW(), 1,1) 01/01/1998 35796.00 =DATE(year(now()),month(now())+1,0) (end of current month) 06/30/1998 35976.00 =DATE(year(now()),month(now())+1,1) 07/01/1998 35977.00 Date entered in Excel 95 Date formatted See additional information below mm/dd/yyyy date serial 1/0/00 01/01/2000 36526 1/0/19 01/01/2019 43466 1/0/20 01/01/1920 7306 The timestamp shown is dependent on cell formatting. Normally a date would appear without a zero time, and a time would appear without a zero date. In XL95 the windowing for 2 digit dates (date window) is 00-19 represents 2000-2019, and 20-99 represents 1920-1999. The windowing dates change with later versions of Excel. XL97 and XL98(Mac) use 00-29 and 30-99.

Last Day of Current Month

Worksheet Function: -- end of Current Month =DATE(year(now()),month(now())+1,0) Programming: end of current month: (NOW is a datetime serial and has both components) ActiveCell.Value = DateSerial(Year(Now), Month(Now) + 1, 0) ActiveCell.NumberFormat = "DDD MM/DD/YYYY" You would actually format the entire column for best usage, without formatting in code. To assign a variable Dim MyDate as Date ActiveCell.Value = DateSerial(Year(Now), Month(Now) + 1, 0)

VBA Examples for Date and TIME (#vba)*


Sub ss1() 'As constants the following will not update [a1] = Int(Now) 'date [a2] = Now 'date and time [a3] = Date 'date [a4] = Date + Time 'same as now 'As Worksheet Functions the following will update [a5] = "=Today()" 'current date into worksheet formula [a6] = "=now()" 'current date [a7] = "=now() - Today()" 'current time when recalculated [a7].NumberFormat = "hh:mm" [a8] = "=MOD(NOW(),1)" 'current time when recalculated [a8].NumberFormat = "hh:mm" End Sub

Comparison of VBA and Worksheet Functions (#comparison)


While col A may have started out as format General, Excel and VBA will change the formatting from General. VBA time and now in VBA will truncate seconds, so you see 06.98 secons from Excel NOW() and 07.00 from the Excel TIME, and 06.00 seconds from VBA. Due to the truncation of seconds, VBA is not going to match your system clock. VBA Excel now() will include fractional seconds. If you want something for timing fractional seconds see Simple Timer on my Slow Response page used to time code to thousandths of a second. I have yyyymm-dd as my date in Regional Settings and hh:mm for my time (not hh:mm A/P). Format as Format as General hh:mm:ss.00 2005-04-20 09:10 09:10:06.00 2005-04-20 00:00:00.00 2005-04-20 00:00:00.00 2005-04-20 09:10 09:10:06.00 Format as Format as Formula or constant =personal.xls!GetFormula(An) 38462.3820138889 38462 38462 38462.3820138889 Formula or constant VBA coding [a2] = Now 'date and time [a3] = Int(Now) 'date [a4] = Date 'date [a5] = Date + Time 'same as now VBA coding

General hh:mm:ss.00 =personal.xls!GetFormula(An) 1900-01-00 09:10 09:10:06.98 =MOD(NOW(),1) [a8] = "=MOD(NOW(),1)" =TIME(HOUR(NOW()),MINUTE( [A9] = "=TIME(HOUR(NOW()), 09:10 AM 09:10:07.00 NOW()),SECOND(NOW())) MINUTE(NOW()),SECOND(NOW()))" 2005-04-20 09:10 09:10:06.00 38462.3820138889 [a10] = Now 'date and time (timestamp) 09:10:06 AM 09:10:06.00 0.382013888888889 [a11] = Time 'time

Adding an interval to a date (VBA code) (#addk)


Adding one month to the 31st in a calendar month can present a problem in interpretation. Here is one solution: To add one month to a date (i.e. 01/28/2001 through 01/31/2001 becomes 02/28/2001) x = DateAdd("m", 1, x - 1)
'yyyy Year, q Quarter, m Month, y Day of year, d Day, w Weekday, ww Week, h Hour, n Minute, s Second

Time is recorded in Days (#days)


Dates and times are both recorded in units of days and the actual number may be referred to as a dateserial or a timeserial. They can be entered in VBA as dateserial(year,month,day) and with timeserial(hour,minute,second). As worksheet functions you would use =DATE(year,month,day) and =TIME(hours,minutes,seconds) You can add the two to get a datetimeserial. Time is recorded in days, so 1 hour = 1/24 day = .0417 day (approx); 1 minute = 1/(24*60) = .000694 days (approx); 1 second = 1/(24*60*60) = . 00001157 days (approx) Assuming that you actually have minutes and seconds multiply by 1440 and format as a number with 2 digits. If on the other hand you really entered as hours and minutes multiply by 24 and format as a number with 2 digits. A display display Days days hours minutes seconds C 0:01:15 0.000868055555555556 1/0/00 12:00 AM =B1 0.00087 =B1 0.000868056 =B1 0.020833333 =B1*24 1.25 =B1*24*60 75.00 =B1*24*60*60 B

1 2 3 4 5 6 7 8

9 10 11 12 13 14 15

display display Days days hours minutes seconds

1:15:00 1/0/00 12:00 AM 0.05208 0.052083333 1.25 75 4500.00

0.0520833333333333 =B9 =B9 =B9 =B9*24 =B9*24*60 =B9*24*60*60

Example: Since 2:15 (2 hours 15 minutes = 0.093750 days) is stored as a fractional day you must multiply by 24 to get 2.25 hours. Suppose you record units in B1 over time in B2 as in transmitting 8 million bytes in 8 minutes, you would put 8000000 in B1 and 0:8:00 in B2. Example: B C D =GetFormula(cell) 1 Bytes 8,000,000 400,000,000 8000000 2 minutes 0:08:00 0:08:00 0.00555555555555556 3 datetimeserial 0.005555556 0.005555556 =B2 4 5 bytes/day 1,440,000,000 72,000,000,000 =B1/(B2) 6 bytes/hour 60,000,000 3,000,000,000 =B1/(B2*24) 7 bytes/min 1,000,000 50,000,000 =B1/(B2*24*60) 8 bytes/sec 16,666.67 833,333.33 =B1/(B2*24*60*60) This is just an example and bears no relationship to any actual transmissions times. A

Date Intervals, Counting (#counting)


A B C

1 12/04/1952 Count of dates within December of any year 2 12/01/1999 6 =SUMPRODUCT(N(MONTH(A1:A20)=12)) 3 11/16/2000 4 11/30/2000 Count of dates found within December, 2000 5 12/01/2000 4 =SUMPRODUCT((MONTH(A1:A20)=12)*(YEAR(A1:A20)=2000)) 6 12/05/2000 7 12/15/2000 Count of dates found between Nov 16, 2000 and Dec 15, 2000 8 12/31/2000 5 =SUMPRODUCT(N(A1:A20>DATE(2000,11,15))*N(A1:A20<=DATE(2000,12,15))) 9 5 =countif(A1:A20,">=11/16/2000")-countif(A1:A20,">12/15/2000")

10 11 02/05/2002 Count of Tuesdays between two dates (i.e. Tue Feb 5, 2002 to Tue Feb 12, 2002) 12 02/12/2002 2 =INT((A12-A11)/7)+IF(WEEKDAY(A11+4)+MOD(A12-A1,7)>=7,1) The first two formulas are based on 2000-11-20 George Simms reply in misc and the third reworked from the first. Cells A9:A20 are BLANK. Note #VALUE! would result if any cell in range was otherwise not numeric. For more information on SUMPRODUCT see Excel HELP. The penultimate solution using COUNTIF was posted by Tom Ogilvy 2000-11-21. The last solution was posted by George Simms 2000-02-19 Date in advanced filter (#filter) "<"&TODAY() -- see Sum Data for references to Advanced Filter.

Adding six months to a date (#add)


Adding six months to a date may have different interpretations. For instance what is six months from a date if the month six months later does not have the same number of days. (see Norman Harker link below)

A B C 1 08/15/2000 02/15/2001 =DATE(YEAR(A1),MONTH(A1)+6,DAY(A1)) 2 08/31/2000 03/03/2001 =DATE(YEAR(A2),MONTH(A2)+6,DAY(A2)) 3 4 08/15/2000 02/11/2001 =A4 + 180 5 08/31/2000 02/27/2001 =A5 + 180 6 7 08/15/2000 02/13/2001 =A7 + 365/2 8 08/31/2000 03/01/2001 =A8 + 365/2 9 10 08/15/2000 02/28/2001 =DATE(YEAR(A10),Month(A10)+7,0) 11 08/31/2000 02/28/2001 =DATE(YEAR(A11),Month(A11)+7,0) 12 13 08/15/2000 02/15/2001 =IF(DAY(DATE(YEAR(A13),MONTH(A13)+6,DAY(A13)))<>DAY(A13),DATE(Y 14 08/31/2000 02/28/2001 =IF(DAY(DATE(YEAR(A14),MONTH(A14)+6,DAY(A14)))<>DAY(A14),DATE(Y A shorter solution than seen in the last two rows adding 6 months is a solution attributed to Chip Pearson as described in a posting (as a tutorial) by Norman Harker (2002-10-13) in worksheet functions adding one month, you can add one month to a Jan 31st date for your own test. =DATE(YEAR(F2),MONTH(F2)+1,MIN(DAY(F2),DAY(DATE(YEAR(F2),MONTH(F2 )+2,0))))

Also See use of DATEDIF on this page, and explanation of DATEDIF Worksheet Function on one of Chip Pearson's pages. Not to be confused with dissimilar DATEDIFF VBA function.

Time Sheets, providing for start and end time through midnight (#thrumidnight)
Time is recorded as fractional days, so 24 hours = 1 day. The following logical formula tests start time (A1) against end time (B1) and adds 1 if A1 is greater than B1. If A1>B1 a true condition exists, value 1 (1=24 hours); otherwise, a false condition exists, value 0
=(A1>B1)+B1-A1 'End time - start time

A more complete example follows that includes break time. A 2 3 4 5 6 7 23:15 0:00 0:00 7:45 8:30 =(A7>B7)+B7-A7+(C7>D7)+D7-C7 John Walkenbach has sample time sheets on his site see Related areas at end of this web page. format of format of E1 E2 23:15 B 3:15 C 4:00 D 7:45 E F

1 START start.break end-break STOP Worked 7:45 =(A2>B2)+B2-A2+(C2>D2)+D2-C2 7.75 =E2*24 h:mm _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)

Entry of Military Time without separations (#military)


The following formula was posted by Glenn Schwandt 1999-11-24 in worksheet.functions utilizing a round down to eliminate right two digits, and a MOD to get the remainder of a divide by 100. A TIME 1 2 3 1200 1201 2400 3359 B C Time =getformula(Bx) 0:01:00 =ROUNDDOWN(A2,-2) / 2400 + MOD(A2,100) / 1440 0:02:00 =ROUNDDOWN(A3,-2) / 2400 + MOD(A3,100) / 1440 0:03:00 =ROUNDDOWN(A4,-2) / 2400 + MOD(A4,100) / 1440 12:00:00 =ROUNDDOWN(A5,-2) / 2400 + MOD(A5,100) / 1440 12:01:00 =ROUNDDOWN(A6,-2) / 2400 + MOD(A6,100) / 1440 0:00:00 =ROUNDDOWN(A7,-2) / 2400 + MOD(A7,100) / 1440 9:59:00 =ROUNDDOWN(A8,-2) / 2400 + MOD(A8,100) / 1440

1 2 3 4 5 6 7 8

Convert to or from Date Serial as Text Constants (#vbadates)


Note the use of Format(cell.Value, "Short Date") which will use your Regional Settings to format the short date.
Sub ConvertFromDateSerial() 'Convert from dateserial to formatted date text constant 'For Excel dateserials on/after March 1, 1900 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range On Error Resume Next '-- in case no cells selected For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlCellTypeConstants)) cell.Value = Format(cell.Value, "Short Date") 'see help for "Named Date/Time Formats (Format Function)" Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub Sub ConvertToDateSerial() 'Convert from recognizable US date to date serial 'For dates on/after March 1, 1900 back to dateserial Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range On Error Resume Next '-- in case no cells selected For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlCellTypeConstants)) cell.Value = Int(DateValue(cell.Value)) cell.NumberFormat = "general" Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Fixup for Dates and Times entered as Text (#fixmmddyyyy)


Assistance to Install a Macro or User Defined Function on my Formula page. Dates are in cells as mmddyyyy and time are hhmm, need to correct these text entries '01312000 to 01/31/2000 and '0136 to 01:36 =DATE(right(a1,4),left(a1,2),mid(a1,3,2) =TIME(left(b1,2),right(b1,2))
Sub Fixmmddyyyy() Dim cell As Range Selection.NumberFormat = "mm/dd/yyyy" On Error Resume Next For Each cell In Selection If Len(cell) = 8 Then cell.Value = DateSerial(Right _ (cell.Value, 4), Left(cell.Value, _ 2), Mid(cell.Value, 3, 2)) End If Next cell Sub Fixhhmm() Dim cell As Range Selection.NumberFormat = "hh:mm" On Error Resume Next For Each cell In Selection If Len(cell) = 4 Then cell.Value = TimeSerial(Left(cell.Value, 2), _ Right(cell.Value, 2), 0) End If Next cell End Sub

End Sub Sub FixhhmmV() Sub fixhhmmss() Dim cell As Range 'posted as fixtime6(), fix mmss, hmmss, Dim vValue As Single hhmmss On Error Resume Next 'DMcRitchie, programming 2001-03-22 For Each cell In Selection Dim x6 As String If InStr(1, cell.NumberFormat,":") = 0 Then Dim cell As Range If cell.Value > 1 Then 'Not a time serial For Each cell In Selection.SpecialCells( _ yet xlCellTypeConstants, xlNumbers) cell.Value = TimeSerial(Int(cell.Value / If cell >= 1 Then 100), _ x6 = Right(Format(cell.Value, "000000"), Int(cell.Value - 100 * Int(cell.Value / 6) 100)), 0) cell.Value = TimeSerial(Left(x6, 2), _ End If Mid(x6, 3, 2), Right(x6, 2)) End If 'cell.NumberFormat = "hh:mm:ss" Next cell End If Selection.NumberFormat = "[hh]:mm" Next cell End Sub End Sub

To change entry at time of entry, Chip Pearson has Date And Time Entry for XL97 and up to enter time or dates without separators -- i.e. 1234 for time entry 12:34.

Using an Array Formula to total by Month (#totbymonth)


A 1 Name 2 Bart 4 Chris 5 Leslie 6 Pat 7 Toby 8 9 Feb 10 Feb Invite Birthdates 7 2 {=SUM((C2:C7)*(MONTH(B2:B7)=2))} {=SUM(1*(MONTH(B2:B7)=2))} B 03/12/1984 02/02/1980 12/25/1975 08/29/1986 02/14/1983 C 3 2 4 1 6 3 The array formula is entered with Ctrl-Shift-Enter do not enter the braces. Read more about Array Formulas on Chip Pearson's site. D

Birthdate Friends Formula

3 Bobby 11/02/1985

A couple more Array formulas, find where is next to 1 or is it 1


=SUMPRODUCT((E3:E24="a")*(F3:F24=1)) enter as array formulas =SUMPRODUCT((E3:E24="a")*(F3:F24="1")) Ctrl+Shift+Enter

Converting Text Dates to Dates (#text2dates)


Either of these methods will create a date serial from the date not dissimilar from how your system is setup. The formatting in the resulting cells will display the date format desired. Now would be a good time to start using four digit dates if you arent already.

1. Use Worksheet Function =Datevalue(text) will convert most anything if the date is in the same format as your system is set up, or 2. Create the dateserial by placing a 1 in a cell on spreadsheet, copy it (Ctrl+C) and then select the column or whatever of text dates and use Paste Special feature with Multiply. Now what to do if the dates are not in the same format as your system. UK text dates (i.e. dd/mm/yy) coming in on a US/Canada system (i.e. mm/dd/yy) to be formatted for US/Canada. You may have to use MID and worksheet function =DATE(year,month,day).

Converting Dates to Text (Dates2Text)


To get a date into text so that it can be left justified and span columns.
=TEXT(NOW(),"mmmm dd, yyyy")

Age in Years, Months, Days using DATEDIF Worksheet Function (#age) (#datedif)
The following shows age in Years + Months + Days A B 1 03/27/1989 3/27/89 2 05/09/1998 =TODAY() same as INT(NOW()) 3 9 =DATEDIF(A1,A2,"y") age in years 4 1 =DATEDIF(A1,A2,"YM") plus months 5 12 =DATEDIF(A1,A2,"md") plus days 6 Calculate number of days to next birthday 7 322 =DATE(YEAR(A1)+A3+1,MONTH(A1), DAY(A1))-A2 Column B shows formula used in Column A, =GetFormula(cell) MS DB KB129277 XL: Undocumented Worksheet Function DATEDIF (** See Next paragraph**) Microsoft has removed DATEDIF from their knowledge database ( thread). Chip Pearson maintains DATEDIF information on his site. In XL95 you must use the Analysis Toolpak add-in. The DATEDIF() worksheet function apparently comes with XL97 and is officially included in XL2000 and documented in the XL2000 help file (you can see here -- xlfctDATEDIF.htm). Later versions of Excel dropped DATEDIF from the help file. When thinking of DATEDIF there is a tendency to forget that the difference between two dates in days is a simple subtraction. KB216578 indicates that DATEDIF is not supported in the Office Worksheet Component meaning it is not available in interactive HTML created from Excel 2000.

Counting Years, Months and Days similar using VBA DATEDIFF to return a three cell array. Tip 55 - John Walkenbach - also gives an idea of what an array formula is and how to implement. KB149689 XL: Visual Basic Macro Examples for Working With Arrays. If you have XL97 or later suggest dumping DATEDIF for John Walkenbachs XDATEDIF Extended Date Functions Add-In, eliminating problems with negative dates involving subtraction in MS date system and incorrect leap years in older MS 1900 date system. (also dates prior to 1900 below). Using DATEDIF in a program The following was posted by Chip Pearson on 6Dec1999 and probably can be found on his site.
Function Age(TheDate As Double) As String Age = _ CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""y"")")) & " years " & _ CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""ym"")")) & " months " & _ CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""md"")")) & " days" End Function

Harlan Grove posted an interesting formula that does not require DATEDIFF to yield age: =YEAR(TODAY()-birthdate)-YEAR(0)

Number of days in a Month (#daysinmonth)


Refer to KB81694 XL: Formula to Calculate Number of Days in Month Examples below for Jul 14, 1998 (07/14/1998) =DAY(DATE(YEAR(The_Date),MONTH(The_Date)+1,0)) 31 =DAY(DATE(YEAR("07/14/1998"),MONTH("07/14/1998")+1,0)) =DAY(DATE(my_year,my_month+1,1)-1) 31 =DAY(DATE(1998,7+1,1)-1)

First, Last, Nearest, Closest, nth weekday (4th Monday) in Month, Date calculations (#firstdate)
WEEKDAY Worksheet Function (1=Sun, 2=Mon, 3=Tues, 4=Wed, 5=Thur, 6=Fri, 7=Saturday) First Monday of Month (day of month 1-7): 1 + correction Third Monday of Month (day of month 15-21): 15 + correction (Dates are shown in US/Canada format mm/dd/yyyy) 04/14/2001 7 Sat 36995 First Day of Week 04/08/2001 1 Sun =B1-WEEKDAY(B1)+1 Last Day of Week 04/14/2001 7 Sat =B1-WEEKDAY(B1)+7 First Day of Month 04/01/2001 1 Sun =DATE(YEAR(B1),MONTH(B1),1)

Last Day of Month First Day of Year Last Day of Year Closest Monday Next Monday Next Monday 1st Monday of Month 2nd Monday of Month 3rd Monday of Month 4th Monday of Month 5th Monday of Month

04/30/2001 2 Mon =DATE(YEAR(B1),MONTH(B1)+1,0) 04/01/2001 1 Sun =DATE(YEAR(B1),MONTH(B1),1) 12/31/2001 2 Mon =DATE(YEAR(B1)+1,1,0) 04/16/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),DAY(B1)+CHOOSE(WEEKDAY(B1),1,0 04/16/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),DAY(B1)+CHOOSE(WEEKDAY(B1),1,7 04/16/2001 2 Mon =A1-WEEKDAY(A1,2)+8 04/02/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),CHOOSE(WEEKDAY(DATE(YEAR(B1) 04/09/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),7+CHOOSE(WEEKDAY(DATE(YEAR(B 04/16/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),14+CHOOSE(WEEKDAY(DATE(YEAR( 04/23/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),21+CHOOSE(WEEKDAY(DATE(YEAR( 04/30/2001 2 Mon =IF(MONTH(DATE(YEAR(B1),MONTH(B1),28+ CHOOSE(WEEKDAY(DATE(YEAR(B
MONTH(B1),1)),2,1,7,6,5,4,3)))=MONTH(B1), DATE(YEAR(B1),MONTH(B1), 28+CHOOSE( WEEDATE(YEAR(B1),MONTH(B1),1)),2,1,7,6,5,4,3)),"none")

3rd Wed. of Month 04/30/2001 4 Wed =A1-DAY(B1)+22-WEEKDAY(B1-DAY(A1)+4) -- Daniel M. Last Monday of Month 04/30/2001 2 Mon =DATE(YEAR($B$1),MONTH($B$1)+1,1)-WEEKDAY(DATE(YEAR($B$
see Date Calculations

Previous Monday 04/09/01 2 Mon =B1-CHOOSE(WEEKDAY(B1,1),6,7,1,2,3,4,5) For a different day of the week rotate the 2nd to last parameters in CHOOSE. i.e. 7,6,5,4,3,2,1 for Wednesday instead of 2,1,7,6,5,4,3 for Monday as used in some of the formulae. Formula in C1 & D1, downward =IF(ISNUMBER(B1),WEEKDAY(B1),"") Formula in E1, downward =personal.xls!getformula(E1) see documentation for this User Defined Funct Weekday(date,1) week starts on Sunday (US default) Numbers 1 (Sunday) through 7 (Saturday). Weekday(date,2) week starts on Monday Numbers 1 (Monday) through 7 (Sunday). Additional formulae and formulae with similar purpose can be found on my Date Calculations page.

Monday week starting dates (#mondaystart)


Week beginning on Monday, will assume Sunday belongs to the previous week of. Format column B as mm/dd/yyyy and column C as ddd. Column C should only show Mon. A2: =TODAY() B2: =A2-MOD(A2-2,7) C2: =B2 programming. format column as mm/dd/yyyy Function Mon_Start(sdate As Date) As Date Mon_Start = sdate - (sdate - 2) Mod 7 End Function

Julian dates, in worksheet (#julian)


Works for numbers or text in the form yyddd, where yy is the year and ddd is the day within year. i.e. 98003, 99003, 00003, 3, 01003, 1003.
=DATE(IF(INT(A1)>39000,INT(A1/1000)+2000,INT(A1/1000)),1,MOD(A1,1000))

These are, of course, the IBM computing Julian dates. The real Julian dates are another matter they begin January 1, 4713 BCE (on the old Julian calendar).

Using fill-handle with Rt-Mouse button to fill in a Calendar of weekdays (#filldates)


You can specify how you want the filling to be done if use the RtMouse button instead of the LtMouse button when you use the fill handle to drag your selection down. After dragging you will be asked what you want to do. || copy values, fill series, fill formats, fill values|| || fill days, fill weekdays, fill months|| || Linear trend, Growth Trend, series ... || with other choices where applicable. More information concerning fill-handle.

Ordinal numbers, and Ordinal numbers in dates (#ordinal)


Ordinal number, any of the numbers first, second, third, etc. (in distinction from one, two, three, etc. which are called cardinal numbers. Also ordinal numeral. 21st and other dates with numbers as 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, etc. =A2&IF(INT(MOD(A2,100)/10)=1, "th", IF(MOD(A2,10)=1, "st", IF(MOD(A2,10)=2,"nd", IF(MOD(A2,10)=3, "rd","th")))) 21st May, 1999 and other dates with days of month as 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, etc. =DAY(A2)&IF(INT(MOD(DAY(A2),100)/10)=1, "th", IF(MOD(DAY(A2),10)=1, "st", IF(MOD(DAY(A2),10)=2,"nd", IF(MOD(DAY(A2),10)=3, "rd","th"))))& " " & TEXT(A2,"mmmm, yyyy") or as a Function
Function OrdDate(arg) dd = Day(arg) mmmm = Format(arg, "mmmm") '*Corrected* yyyy = Year(arg) Select Case Day(arg) Case 1, 21, 31 OrdDate = dd & "st " & mmmm & ", " & yyyy Case 2, 22 OrdDate = dd & "nd " & mmmm & ", " & yyyy Case 3, 23 OrdDate = dd & "rd " & mmmm & ", " & yyyy Case 4 To 20, 24 To 30 OrdDate = dd & "th " & mmmm & ", " & yyyy End Select End Function

A macro by Ron Rosenfeld (see thread) changes the format rather than the text. The macro is written for XL97 and has an advantage in not using a second cell to display a text format. Written as a Worksheet_Change macro it will change the format for all dates on a particular worksheet when they are entered, changed or recalculated. The big advantage is that the cell can continue to be treated as a numeric value.

Last Saved Date (#lastsaved)


=FileDateTime(ActiveWorkbook.FullName)

Also see use in Pathname in headings, footers, and cells. Will create a documentation page someday with all the documentation items and include the following Thomas Ogilvy reference: Read a Disk Directory to into a Spreadsheet, also see properties.

Create a new worksheet with 1 weeks worth of dates (#sheetwithdates)


Create a new worksheet one week of dates down Column A. Dates created for the current week. Example run on Fri 12/29/2000. Constants for dates are generated not formulas with date functions.
Option Explicit Sub Macro39() Sheets.Add Range("1:1,A:A").Font.Bold = True Columns("A:A").Select Selection.NumberFormat = "ddd mm/dd/yyyy" Range("a2").Formula = Int(Now()) _ - Weekday(Int(Now())) + 1 Range("A2").AutoFill _ Destination:=Range("A2:A8"), _ Type:=xlFillDefault Range("a1").Formula = _ Format([a2], "mm/dd/yy") & Chr(10) _ & " - " & Format([a8], "mm/dd/yy") Columns("A:A").EntireColumn.AutoFit Range("B2").Select ActiveSheet.Name = "D." & Format([a2], _ "yyyymmdd") 'rename sheet End Sub

1 2 3 4 5 6 7 8

A B 12/24/00 - 12/30/00 Sun 12/24/2000 Mon 12/25/2000 Tue 12/26/2000 Wed 12/27/2000 Thu 12/28/2000 Fri 12/29/2000 Sat 12/30/2000

Week number -- European Style -- ISO Standard 8601 (#weeknumber)


The following formula was posted by Laurent Longre (1999-08-10), D is the date.
=INT((D-SUM(MOD(DATE(YEAR(D-MOD(D-2,7)+3),1,2),{1E+99,7})*{1,-1})+5)/7)

In Europe weeks begin on a Monday and end on Sunday, even so the formula =WEEKNUM(date,2) which indicates that weeks begin on Monday will not work for European

usage. In the US the first week begins on January 1st, so the first week and the last week of a year may both have less than 7 days. In the European style (ISO 8601) the week begins on a Monday and includes the first Thursday of the new year. The reason for Thursday is that the majority of the days in the Mon-Sun week will be in the new year. This is the same as saying the week with Jan 4th will always be the first week. For additional information see A Summary of the International Standard Date and Time Notation at http://www.cl.cam.ac.uk/~mgk25/iso-time.html which contains information on ISO 8601 and references additional material. Also see Pat McCotter's posted an article 1999->03->20. Chip Pearson has followed this more closely you can find out more about week numbers, including English postal service on Chips site.

Date & Time Worksheet Functions in Excel (#ws)


Refer to your HELP (F1)file for more information. DATE Returns the serial number of a particular date syntax: DATE(year, month, day DATEVALUE Converts a date in the form of text to a serial number Example: =DATEVALUE("8/22/55") equals 20323 DAY Converts a serial number to a day of the month DAYS360 Calculates the number of days between two dates based on a 360-day year EDATE Returns the serial number of the date that is the indicated number of months before or after the start date syntax: EDATE(start_date, months) Example: =EDATE(DATEVALUE("01/15/91"),1) equals 33284 or 02/15/91 Example: =TEXT(EDATE(DATEVALUE("January"&" 15, 1999"),1),"mmmm") equals February EOMONTH Returns the serial number of the last day of the month before or after a specified number of months HOUR Converts a serial number to an hour MINUTE Converts a serial number to a minute MONTH Converts a serial number to a month NETWORKDAYS Returns the number of whole workdays between two dates.
NETWORKDAYS(start_date,end_date,holidays) NETWORKDAYS("10/01/1998","12/01/1998","11/26/1998")

NOW SECOND TIME TIMEVALUE TODAY

Result of above is 43 (61 days between). Also see WORKDAY. Returns the serial number of the current date and time Converts a serial number to a second Returns the serial number of a particular time Converts a time in the form of text to a serial number Example: =TIMEVALUE("2:24 AM") equals 0.1 Returns the serial number of todays date

WEEKDAY

WORKDAY

Converts a serial number to a day of the week Example: =WEEKDAY("2/14/907quot;) equals 4 (Wednesday), similarly Example: =TEXT("4/16/90", "dddd") equals Monday Returns the serial number of the date before or after a specified number of workdays. This is the opposite of NETWORKDAY.
WORKDAY(start_date,days,holidays)

YEAR YEARFRAC

Converts a serial number to a year Returns the year fraction representing the number of whole days between start_date and end_date

Time Difference Calculations (#timediff)


Subtracting Time (#subtracttime)
A B C End 10:55 8:20 D E 0.00 2.58 D3: =C3-B3+(B3>C3) E3: =24*D3 F G

1 Format--> General General [h]:mm 2 Employee Start 3 Jan H. 4 Pat T. 8:20 10:55 2:35

Duration Hours =GetFormulaD(address) 21:25 21.42 D4: =C4-B4+(B4>C4) E4: =24*D4

The formula to subtract times where the ending time might look like an earlier time would be: =C3-B3+(B3>C3) The last part is a logical expression that adds 1 if start time is greater than end time, or 0 otherwise. Time is measured in days so the addition of 1 is adding 24 hours to the equation. You subtract one time from the other. The result should be formatted as time but since you might end up with more than 24 hours you would format as [h]:mm instead of h:mm

Rounding Time value to Quarter Hour (#rndqtrhr)


Remember time is stored as days, so one quarter hour is 1/(24*4) days or .01041666 days. The fraction will be more accurate. MROUND is part of the Analysis Toolpak Add-in. Rounding to nearest quarter hour: Rounding down to nearest quarter hour: Rounding Up to nearest quarter hour: Rounding Up to nearest half hour: =MROUND(A22,1/(24*4)) =FLOOR(A22,1/(24*4)) =CEILING(A22,1/(24*4)) =CEILING(A22,1/(24*2))

Consulting Fees (#fees)


C D E F G H I J

8 9 10 11 12 13

hh:mm 4:06 7:29 7:31 8:00 37:30

Rounded Billed @ HRS Rate/HR hh:mm $100/HR 4:30 4.5 7:30 7.5 8:00 8.0 8:00 8.0 37:30 37.5 100.00 100.00 100.00 100.00 $ 45.00 $ 75.00 $ 80.00 $ 80.00

Addr Formula C9 D9 E9 F9 G9 0.170833333333333 = ROUNDUP(C9*48,0)/48 = ROUNDUP(C9*48,0)/2 100 =F9 * ROUNDUP(C9*48,0)/2

100.00 $ 375.00

Wages calculation with C9 having a time in hh:mm and you want to round up at 1/2 hour intervals shown in D9. Column C is formatted as [hh]:mm =Roundup(c9*48,0)/2 =100* ROUNDUP(C9*48,0)/2 format as 0.0 for decimal hours format as dollars not a time

Time is measured in days, 24 hours in 1 day. The roundup calculation does not handle fractions so multiply 24 by 2 get the roundup and then divide by 2

Calculating hours outside of Core range (#core)


The basic concept is: number of hours before core hours + number of hours after core hours =IF(Shift_Start<Core_Start, Core_Start-Shift_Start,0) + IF(Shift_End>Core_End, Shift_End-Core_End,0) but since time is not recorded with the dates this becomes more complicated.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > -- corrections to formulas 2002-02-09 to fix errors when converted to HTML--c3: =B3-A3+(A3>B3) is equivalent to =IF(B3>A3,B3-A3,B3-A3+1) d3: =IF(B3>=A3,MAX(MIN(B3,G3)-A3,0)+MAX(B3-H3,0), MIN(B3+1,1+G3)-MAX(A3,H3)) e3: =IF(ABS(D3-F3)<0.0001,"yes","NO") f3: is the goal, it is what is to be expected from the calculations G3 is the Core.start time H3 is the Core stop time Don't know if this is a concern or not: If clock time goes through midnight and core start and stop times it will be incorrect, but your elapsed hours would exceed 16 hours as seen in my last tested values. David McRitchie (1999/08/01) Tested example: --A-- --B-- --C-- --D-- -E- --F-- --G-- --H-Start Stop Elap calc. ^^^ GOAL c.start c.ent 23:00 07:00 08:00 08:00 yes 08:00 07:00 15:00 00:00 08:00 08:00 07:00 yes 07:00 07:00 15:00 03:00 11:00 08:00 04:00 yes 04:00 07:00 15:00 12:00 20:00 08:00 05:00 yes 05:00 07:00 15:00 16:00 00:00 08:00 08:00 yes 08:00 07:00 15:00 12:00 20:00 08:00 05:00 yes 05:00 07:00 15:00 23:00 15:00 16:00 08:00 yes 08:00 07:00 15:00 00:00 16:00 16:00 08:00 yes 08:00 07:00 15:00 03:00 19:00 16:00 08:00 yes 08:00 07:00 15:00 12:00 04:00 16:00 13:00 yes 13:00 07:00 15:00

> > > > > > > > > > > > > > > > > > > > > > > > > > > > >

16:00 00:00 04:00 08:00 12:00 16:00 20:00 00:00 04:00 08:00 04:00 06:00

08:00 16:00 20:00 00:00 04:00 08:00 12:00 16:00 04:01 08:01 04:00 05:00

16:00 16:00 16:00 16:00 16:00 16:00 16:00 16:00 00:01 00:01 00:00 23:00

15:00 08:00 08:00 09:00 13:00 15:00 11:00 08:00 00:01 00:00 00:00 14:00

yes yes yes yes yes yes yes yes yes yes yes NO

15:00 07:00 15:00 08:00 07:00 15:00 08:00 07:00 15:00 09:00 07:00 15:00 13:00 07:00 15:00 15:00 07:00 15:00 11:00 07:00 15:00 08:00 07:00 15:00 00:01 07:00 15:00 00:00 07:00 15:00 00:00 07:00 15:00 15:00 07:00 15:00 == failed should be 15 hours not 14 hours.

Similar information in a little different format, basically switch usage of G & H columns. Rate ---> 1 1.5 Start End Norm. Prem. -- -Time Time Hours Hours -17:00 01:00 03:00 05:00 01:00 09:00 08:00 05:00 09:00 17:00 08:00 00:00 17:00 01:00 08:00 05:00 01:00 09:00 08:00 05:00 09:00 17:00 08:00 00:00 C3: D3: Extra paid Extra Pay hours -- From To --20:00 --20:00 --20:00 --20:00 --20:00 --20:00 hours 6:00 6:00 6:00 6:00 6:00 6:00

=B3-A3+(A3>B3)-D3 =IF(B3>=A3,MAX(MIN(B3,H3)-A3,0)+MAX(B3-G3,0), MIN(B3+1,1+H3)-MAX(A3,G3))

To show time as a hours with decimal fraction multiply Excel hours by 24.

-----The following formula was posted 2002-02-09 by Daniel Maher and fixes a problem that I indicated in the first example. This solution is for the second example. Will at least be including this until I fix my own formula. DanielM 2002-02-09 =IF(CheckOut>=CheckIn,MAX(0,MIN(CheckOut,UpperBound)A B C D E MAX(CheckIn,LowBound)),MAX(0,UpperBound-MAX(CheckIn, in out of LowBound))+MAX(0,MIN(CheckOut,UpperBound)-LowBound)) 1 IN OUT reported core core For the time OUTSIDE the boundaries 2 6:00 14:00 8:00 6:00 2:00 of [LowBound ... UpperBound], it is 3 0:00 12:00 12:00 4:00 8:00 =(checkout<checkin)+CheckOut-CheckIn4 12:00 0:00 12:00 6:00 6:00 Big_Formula_Above 5 18:00 9:00 15:00 1:00 14:00 6 23:00 12:00 13:00 4:00 9:00 If you want the HOURS, multiply by 24. C2: =(B2<A2)+B2-A2 D2: =IF(B2>=A2,MAX(0,MIN(B2,"18:00")-MAX(A2,"8:00")),MAX(0,"18:00"MAX(A2,"8:00"))+MAX(0,MIN(B2,"18:00")-"8:00")) E2: =(B2<A2)+B2-A2 - D2 grayed area for reference not used in calculation of columns D & E (B2<A2) is a logical express equates to either 1 (i.e. 24 hours), or 0 to be added/subtracted ------

Total core hours (9AM-5PM) between two datetimestamps, but only weekdays
On 8/8 8/9/1999 JM (jmklee) reply to Anthony R. Acosta. (accepted as is) I would like to calculate the difference in minutes between two dates, excluding the hours between 5pm to 8am and weekends. For example if the first date is 08/04/99 6:00pm and the end date is 08/05/99 9:00 am, I would like it to calculate as 60 minutes or one hour. You can use the NETWORKDAYS function from the Analysis Tool. A1 your first date and B1 your end date, both in full format mm/dd/yy hh:mm You can have A1 and B1 separated with as many days you want. The total time is in C1 (formatted with [h]:mm ) : You might want to use notepad to eliminate end of line characters from these formulas: A B Sat 1 12/01/2001Mon 12/03/2001 16:00 07:00 2 =A6+A4 =A8+A6 3 4 8:00 Length of core hours for one day 5 7:00start time (doesnt count until either 8AM or 9AM) on 1st day 6 16:00end time (one hour short on 9AM-5PM) on last day 7 12/01/2001start date 8 12/03/2001end date 9 10 07:00Original Formula with NETWORKDAYS 9:00 - 17:00 original 11 08:00Original Formula with NETWORKDAYS but 8:00-16:00 instead of 9:00-17:00 12 23:00Formula without NETWORKDAYS corrected to use 9AM to 5PM 13 24:00Formula without NETWORKDAYS corrected to use 8AM to 4PM (spaces in formula removed) 14 24:00Formula without NETWORKDAYS corrected to use 8AM to 4PM (spaces in formula removed) 15 Formulas used in A9:A12 note 8 hour interval, with specific time range =MIN("8:00",MAX("0:00","17:00"+INT(A1)A1))*NETWORKDAYS(A1,A1)+MIN("8:00",MAX(B1-"9:00"16 07:00 INT(B1)))*NETWORKDAYS(B1,B1)+"8:00"*(MAX(0,NETWORKDAYS(A1,B1)-2)(INT(INT(A1)/INT(B1)))) =MIN("8:00",MAX("0:00","16:00"+INT(A1)A1))*NETWORKDAYS(A1,A1)+MIN("8:00",MAX(B1-"8:00"17 08:00 INT(B1)))*NETWORKDAYS(B1,B1)+"8:00"*(MAX(0,NETWORKDAYS(A1,B1)-2)(INT(INT(A1)/INT(B1)))) =MIN("8:00",MAX("0:00","17:00"+INT(A1)-A1)) +MIN("8:00",MAX(B1-"9:00"-INT(B1))) 18 23:00 +"8:00"*(MAX(0, INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1))) =MIN("8:00",MAX("0:00","16:00"+INT(A1)-A1))+MIN("8:00",MAX(B1-""8:00""-INT(B1))) 19 24:00 +"8:00"*(MAX(0,INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1))) =MIN(A4,MAX("0:00","16:00"+INT(A1)-A1))+MIN(A4,MAX(B1-"8:00"-INT(B1))) 20 24:00 +A4*(MAX(0,INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1)))

Problems entering Date or Time when Transition options in effect (#date123)

Lotus 1-2-3 transition options interfere with entry of date and times, would suggest turning them off after all you are using Excel not 1-2-3. Under Tools --> Options --> Transition turn off everything that says transition, and hit the [OK] button The DateWatch utility (or a similar 3rd-party program) can cause problems with entering fractions, it appears under tools menu as Date Migration, and can be turned off through Tools/Addins menu. Rob Bovey 1999->01->15 <uVKu548X GA.205@cppssbbsa04>

Problems enter Fractions, but get Dates (#entryprob)

Entering stock prices as 1/2 or 1/64 and getting dates: Solution enter 0 1/2 or 0 1/64 instead. See Pasting fractional stock prices show up as dates in Excel for an attempt at fixing.

Countdown to a Date (#countdowny2k)


Countdown to the New Millennium (year 2001). Some additional Excel 2000 tips.
=DATEVALUE("1-January-2001")-TODAY()&" days remaining in 2000"

VBA -- Visual Basic for Applications (Programming Language) -- VBA

Date & Time Functions in VBA (#vbadate)


Refer to your VBA HELP file for more information. VBA Help is obtained where you can edit your code. In XL97 and up it is Alt+F11, then F1, and in XL95 invoke F1 (Help) when editing a module sheet. Date DateDiff Returns a Variant (Date) containing the current system date. DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]]) Dont confuse this with the DATEDIF Worksheet Function

DateSerial DateSerial(year, month, day) DateValue DateValue(date) -- MyDate = DateValue("February 12, 1969") Day Hour IsDate Minute Month Now Second Day(date) Hour(time) -- returns integer between 0 and 23 IsDate(expression) -- returns True or False Minute(time) -- returns 0 to 59 Month(date) Now -- Returns a Variant (Date) specifying the current date and time according your computers system date and time. Second(time) -- returns whole number between 0 and 59, inclusive

TimeSerial TimeSerial(hour, minute, second) TimeValue TimeValue(time) -- MyTime = TimeValue("4:35:17 PM") Weekday Weekday(date, [firstdayofweek])

Year

Year(date)

If you want absolute control over adding a number of months to another date where the day of the month of the first date does not exist in the date that is xx months later.
Function Addmonths(dateref As Date, _ add_months As Long, Optional nextmonth as boolean) As Date Addmonths = Application.Min(DateSerial(Year(dateref), _ Month(dateref) + add_months, Day(dateref)), _ DateSerial(Year(dateref), Month(dateref) + add_months + 1, nextmonth)) End Function

ISDATE (a builtin VBA function)

(#isdate)
Sub Ratman02() Cells.Interior.ColorIndex = 0 'reset all interior color Dim cell As Range For Each cell In Application.Intersect _ (Selection, ActiveSheet.UsedRange) If IsDate(cell) Then If cell.Value > Date Then cell.Interior.ColorIndex = 3 'Red - FUTURE DATE Else cell.Interior.ColorIndex = 8 'Cyan -- valid date End If Else: cell.Interior.ColorIndex = 14 'Teal -- NOT a Date End If Next cell End Sub

This example was tested on 08/05/2000 (Aug 5, 2000 US Format) A B C D 10 11 08/01/2000 12 09/01/2000 08/05/2000 13 08/05/2000 10/01/2000 14 08/05/2000 08/05/2000 15 08/05/2000 Hello 16 08/05/2000 08/05/2000 17

More information on Colors in Excel and the Excel color palette.

Converting Text Dates to Excel Dates (#MakeTrueDate)


If the Text dates and your Regional Dates are both US date format, for a manual conversion: - Copy an empty cell - Select Range for cells to be converted - Edit, Paste Special, Add - Format range as Date An alternative is to copy a 1f and use Paste Special with Multiply instead. Use of a macro simply needs to reassign the value and Excel will recognize it as a date. (only if your date formats are US)
Sub MakeTrueDate() 'Converts Text Dates(US) to dates(US), Tom Ogilvy, 2001-03-24 programming Dim rng As Range Set rng = Intersect(ActiveCell.EntireColumn, _ ActiveSheet.UsedRange) 'next assume first row is a header Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1) rng.NumberFormat = "mm/dd/yyyy" rng.Value = rng.Value

End Sub

Converting Text Entry Dates to Excel Dates with Text to Columns (#t2cols)
What to do when Text Entry Dates Do NOT Match your Regional Settings Converting Text entry dates to Excel dates is easily done by multiplying by 1, but when the date entries do not match your regional settings you can use Text to Columns to fix up your dates. Actually this would be more of a problem for those with UK/European/Australian dates than those with US dates. My dates are US and my Regional short date is mm/dd/yyyy which having US dates is assumed to be m/d/y. If you specify a month greater than twelve, Excel will assume you reversed the day and month -- there is such an example below. This question was raised by someone in Australia working with MetaStock which generates an Excel spreadsheet with US text dates instead of UK/Australian dates. C D E F Single column processed with 1 Original Specified format for F3:G8 Text to Columns 2 Text to Columns (source) MDY DMY MDY DMY 3 Format on row 4 @ m/d/yy m/d/yy ddmmmyyyy ddmmmyyyy 4 Date 4/5/99 04/05/1999 05/04/1999 05Apr1999 04May1999 5 Date 3/4/00 03/04/2000 04/03/2000 04Mar2000 03Apr2000 6 Date 9/10/99 09/10/1999 10/09/1999 10Sep1999 09Oct1999 7 Date 12/13/99 12/13/1999 12/13/1999 13Dec1999 13Dec1999 8 Date 13/12/01 13/12/01 12/13/200113/12/01 13Dec2001 9 Date 24/9/01 24/9/01 09/24/200124/9/01 24Sep2001 10 shows alignment ooo oooooooooooo ooooooooooooo ooooooooooooo ooooooooooooo ooooooooooooo A B

Adjusting Date Time Stamps from other systems (#adjust)


UNIX maintains date and time as seconds past Jan 1, 1970. Convert to Excel use with = DATE(1970, 1, 1) + (A1/24/60/60) More information J.E. McGimpsey, 2001-09-26and function.

Debugging Date Entries (#debug)


Regional settings and cell formatting can cause problems with dates if anything is incorrectly applied. This topic is to help you identify what you actually have. One thing you can do to quickly determine if entries are Text or Numbers is to use: Select ALL cells (Ctrl+A), Edit (Ctrl+G), [Special], GoTo, Number & Constants (only constants)

Dates are Numbers. The format for a number can be changed at any time to another number format. Data that was entered as text or with a text format must be reentered if the format is changed to a number format. By formatting the cell range, then reentering the value you can convert text entries containing numbers to number constants. The fastest way to reenter a single cell is to select cell, press F2, then Enter. You can convert a lot of text entries containing numbers to number constants by multiplying by 1 or by adding a blank (truly empty) cell. Select empty cell and copy (ctrl+c) then select the range, then edit, paste special, add. You can effect a similar change by selecting a cell with a value of 1, copy (ctrl+c), select the range to be affected, paste special, multiply. You can use one of the REENTER macros on my Reformat page (join.htm) to speed up the process, there are several variations there, including TrimALL which specifically converts CHAR(160) which is the HTML symbol &nbsp; (non breaking space) to a space then trims spaces from the left and right sides of the cell value.

1 2 3 4 5 6 7 8 9 10 11

Regional Dates in use are US: short: mm/dd/yyyy long: mmmm dd, yyyy -- Some entries (E16:E25) below have formats overridden in cell. A B C D E F G DATE The Example to the left has entry as Display Formula ENTRY 6/7/99 and my Regional Settings are for the US, but Entered as 6/7/99 with US Regional 06/07/1999 my short date Settings regional setting is modified to include 06/07/1999 5 =LEN(A3) the full 4 digit 06/07/1999 36318 =TEXT(A4,"General") year so my Regional Setting Short =TEXT(A5,"dd mmm Date format is 06/07/1999 07 Jun 1999 yyyy") mm/dd/yyyy -- interestingly the format =TEXT(A5,"mmm dd, shows as 06/07/1999 Jun 07, 1999 yyyy") m/d/yy because that is the default US 06/07/1999 TRUE =ISNUMBER(A7) regional setting. 06/07/1999 D4 =CELL("format",A8) Note cell B35 has code 0160 06/07/1999 v =CELL("type",A9) simulating an HTML 06/07/1999 36318 =getformula(A10) symbol of &nbsp; (non breaking 06/07/1999 m/d/yy =getformat(A11) space). When trying to debug date entries note what you see 1) in the formula bar 2) in the cell 3) in the format (Format, cell)

12 06/07/1999

56 =CODE(RIGHT(A12,1))

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 DATE Display Formula ENTRY 06/07/99 Entered as shown on Formula bar 07/06/1999 5 =LEN(A16) 07/06/1999 36318 =TEXT(A17,"General" =TEXT(A18,"dd mmm 07/06/1999 07 Jun 1999 yyyy") =TEXT(A18,"mmm dd, 07/06/1999 Jun 07, 1999 yyyy") 07/06/1999 TRUE =ISNUMBER(A20) 07/06/1999 D1 =CELL("format",A21) 07/06/1999 v =CELL("type",A22) 07/06/1999 36318 =getformula(A23) 07/06/1999 dd/mm/yyyy =getformat(A24) 07/06/1999 56 =CODE(RIGHT(A25,1)) has Char(160) Display Formula so is text 06/07/99 has Char(160) 06/07/99 9 =LEN(A28) 06/07/99 06/07/99 =TEXT(A30,"General" =TEXT(A31,"dd mmm 06/07/99 06/07/99 yyyy") =TEXT(A31,"mmm dd, 06/07/99 06/07/99 yyyy") 06/07/99 D1 =CELL("format",A33) 06/07/99 l =CELL("type",A34) 06/07/99 FALSE =ISNUMBER(A35) 06/07/99 06/07/99 =getformula(A36) 06/07/99 dd/mm/yyyy =getformat(A37) 06/07/99 160 =CODE(RIGHT(A38,1)) TEXT ENTRY 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 Display Formula

Entered with quote on Formula bar 6 =LEN(E16) 36318 =TEXT(E17,"General" 07 Jun =TEXT(E18,"dd mmm 1999 yyyy") Jun 07, =TEXT(E18,"mmm dd, 1999 yyyy") FALSE =ISNUMBER(E20) G =CELL("format",E21) l =CELL("type",E22) 6/7/99 =getformula(E23) General =getformat(E24) 57 =CODE(RIGHT(E25,1))

Column is Display Formula Text 6/7/99 Entered into Text field 6/7/99 6 =LEN(E28) 6/7/99 36318 =TEXT(E30,"General" 07 Jun =TEXT(E30,"dd mmm 6/7/99 1999 yyyy") Jun 07, =TEXT(E30,"mmm dd, 6/7/99 1999 yyyy") 6/7/99 G =CELL("format",E33) 6/7/99 l =CELL("type",E34) 6/7/99 FALSE =ISNUMBER(E35) 6/7/99 6/7/99 =getformula(E36) 6/7/99 @ =getformat(E35) 6/7/99 57 =CODE(RIGHT(E36,1))

Bus Schedule with PM times as boldface (#bus)


You cannot specify boldface in regular cell formatting. Conditional Formatting could do the boldface but that is all. A macro is needed to change the time and formatting so that that 1:00 and 13:00 both appear as 1:00 with the PM appearing in bold, and both without AM or PM. Example: Original Bus Schedule Sheet A B C D New Bus Schedule Sheet A B C D

3 8:00Point B 7:00Point F 4 12:00Point C 12:00Point E 5 13:00Point D 16:00Point D 6 17:00Point E 17:00Point C

3 8:00Point B 7:00Point F 4 12:00Point C 12:00Point E 5 1:00Point D 4:00Point D 6 5:00Point E 5:00Point C

A more complete example with code can be seen on Bus Schedule page

Coverage Chart (#coverage)


A 7 NAME 8 Arlene B C D E F G H I J K L M N O P Q R S T U

HRS 8 7.5 9 Betty 7.0 10 Cathy 7.5 X X 11 Coverage 1 1

9 XX X XX 2 3

10 X X X 3

X X X 3

11 12 X XX X X XX X X 3 2 2 2

13 14 15 X XX X X X XX X X XX 3 2 2 2 3

X X X 3

16 X X X 3

17 X X XX 3 1

B8: =COUNTA($C8:$U8)*0.5 C11: =COUNTA(C$8:OFFSET(C11,1,0)) Conditional formatting for the range C8:U10 CF1: =COUNTA(C8) CF2: =NOT(COUNTA(C8))

1904 Date System vs 1900 Date System (#1904)


The difference in days between the two systems is 1462, which you may encounter if you try to change the date system in a workbook, or if you copied a worksheet from another workbook. Tools, Options, Calculation, 1900/1904 Dates

Real-Time Clock in Excel (#clock)


Sometimes someone wants a real-time clock in their worksheet. Personally I think the System time in the corner of the screen serves this purpose, and there are shortcuts for entering System Date/Time into a Cell or within code. The solution here will produce screen blinking as the clock updates at one second intervals which may differ by up to one second from the system clock in your computer. For time from the National Institute of Standards and Technology (NITS), see Time Information topic for more information.
From: Harald Staff

12:35:17 AM X

xxxxx

Here is code for a clock that runs in worksheet one, cell A1, unless You type X in B1, then it stops. Modify location and criteria&rsquos for Your own use.

Sub clock() If ThisWorkbook.Worksheets(1).Range("B1").Value = "X" Then Exit Sub ThisWorkbook.Worksheets(1).Range("A1").Value = Format(Now, "hh:mm:ss AM/PM") Application.OnTime Now + TimeSerial(0, 0, 1), "clock" End Sub Best wishes Harald (I got this code from this group some months ago, and I am sorry that I did not archive the creator for later credits. Thank You, whoever You are.) See revised Real-Time Clock (below).

Revised Real-Time Clock


Similar to the above. Harold supplied a revised version that recommends use of a start button and a stop button. Instead of simply replacing the coding I have included both so you can see the coding. I see the cursor move and blink momentarily every second on XL95. You can create buttons using the Tools Form bar. The buttons would not ordinarily coincide with cell boundaries, but they could appear to as in the following example. Again repeating what was said before: Personally I think the System time in the corner of the screen serves this purpose, and there are shortcuts for entering System Date/Time into a Cell or within code. A clock on the worksheet will be stealing cycles whether you see the clock or not, even if the page isnt active, and you will probably notice a slow down with large workbooks. You can show seconds on the Task Bar Clock by using TClockEx without turning your expensive computer into a wall clock.

12:35:17 AM

Start Stop Clock Clock

Dim stopit As Boolean 'on top of module! Sub startclock() 'assign start button stopit = False clock End Sub Sub clock() If stopit = True Then Exit Sub ActiveWorkbook.Worksheets(1).cells(1, 1).Value = _ Format(Now, "hh:mm:ss") Application.OnTime (Now + TimeSerial(0, 0, 1)), "clock" End Sub Sub stopclock() 'assign stop button stopit = True End Sub

Note the Worksheets(1). This indicates the first worksheet in your workbook. You might want to change that to a specific sheet such as Worksheets("Clock Sheet") or Worksheets("Sheet7") so as to not wipe out any sheet that just happens to have become the first sheet. This also applies to the previous example.

Elapsed Time and Count-Down Timer (#timers)


See chrono.zip on Steve Bullens site. See this thread in Google Usenet Archives, specifically look for Stephen Bullens reply.

Stop Watch, Alarm, and Count Down Timers


Excel does not have a SLEEP function so you have to calculate the time at which you will resume. The following will issue three beeps, I give a little more time after the first beep. I still see timing done with a loop to waste machine cycles. On a mainframe that would be well over 30 years behind the times. Anyway I think the code I have below will work better across platforms and more to the point with processors with different speeds instead of a timing loop.
Sub Beeper() Beep start2 = Now() + TimeSerial(0, 0, 0.9) Application.Wait start2 For i = 2 To 3 start2 = Now() + TimeSerial(0, 0, 0.8) Application.Wait start2 Beep Next i End Sub

Stopwatch to time inner processing in seconds. Timer is the number of seconds since midnight, so a correction has been included for negative number resulting from passing through midnight during execution. (Limited to duration of 24 hours, longer times possible by including date) -- also see More on Stop Watches below.
Sub Timing_Test() Dim timing As Double 'timing will be shown at end timing = Timer 'Floating point register used ' .... lots of processing here .... timing = Timer - timing if timing < 0 then timing = timing + 1440 'midnight correction MsgBox Format(timing, "0.000") & " seconds" End Sub

This example will sound an Alarm at a specified time.


Sub Alarm() Dim beepat As String beepat = InputBox("Give Alarm at", "hh:mm:ss " & _ Format(Now, "mm:hh"), "17:00") If beepat = "" Then MsgBox "cancelled" Exit Sub End If

Application.OnTime TimeValue(beepat), "BeepMe" End Sub

Example of a Count Down Timer


Sub CountDownTimer() Dim beepat As String beepat = InputBox("Count down Timer hh:mm:ss i.e. 10:00", _ "Time now is " & Format(Now, "hh:mm:ss"), "3:00") If beepat = "" Then MsgBox "cancelled" Exit Sub End If Application.OnTime (Now + TimeValue(beepat)), "BeepMe" End Sub Sub beepme() Beep Application.OnTime (Now + TimeSerial(0, 0, 0.8)), "beepme2" End Sub Sub beepme2() Beep Application.OnTime (Now + TimeSerial(0, 0, 0.8)), "beepme3" End Sub beepme3() Beep End Sub

More on Stop Watches -- Continued (#StopWatchcontd), Also take a look at my page on Slow Response Inevitably someone is going to try to use Excel to time runners to 100ths of a second. Without examining whether Excel is really feasible for this or not here are some newsgroup searches on how to do it. The best solutions will probably require winmm.dll for high resolution. All were found starting with: http://groups.google.com/advanced_group_search? q=group:*Excel*&num=100 search on all words: "stop watch" real group:*excel* threadm=3A782332.5D8EC99E%40consumer.org search on all words: stopwatch record group:*excel* selm=eldUXJUlCHA.2000%40tkmsftngp04 threadm=66sapo%2448e%241%40news-srv1.fmr.com

Dates formatted in a VBA macro subroutine (#vbaformat)


As text [a10].Value = Format(Now, "mm/dd/yyyy hh:mm:ss AM/PM") Range("A11").Value = Format(Now, "hh:mm:ss") activecell.offset(0,4).value = Format(Now, "hh:mm:ss") Assign datetime interval constant and format as date/time

activecell.offset(0,4).format = "mm/dd/yyyy hh:mm:ss AM/PM" activecell.offset(0,4).value = Now

Dates Prior to 1900 and George Washingtons birthday (#gwash)


John Walkenbach has created as an addin to handle years 0100-9999 in his Extended Date Functions Add-In, which requires at least XL97. 0100-9999 is the date range supported by VBA, so dont know what calendar changes, if any, are actually supported. I dont know which calendars are in use in Johns XDATE functions but anything has to be better than what is builtin to Excel. I will mention the following excerpt from the 1990 World Almanac to highlight some difficulties of working with older dates. The British Government imposed the Gregorian calendar on all its possessions, including the American colonies, in 1752. The British decreed that the day following Sept. 2, 1752, should be called Sep. 14, a loss of 11 days. All dates preceding were marked O.S., for Old Style. In addition New Years day was moved to Jan. 1 from Mar. 25. George Washingtons birth date, which was Feb. 11, 1731, O.S., became Feb. 22, 1732, N.S. What is now the US had three different dates for the Julian to Gregorian calendar shift alone - 1582 for the areas under Spanish and French control, 1752 for areas under British control, and 1863 for Alaska, when it was purchased from Russia. I think everyone would agree that that Excel is severely lacking in its ability to work with date calculations such as dates in 1800 especially since there are people living who were born in 1800s and in treating 1900 as a leap year as had one of its predecessors, Lotus 1-2-3. General Information on Date and Time (not necessarily related to Excel)

Time Information, for those who are serious or just interested (#timeinfo)
If you computer clock is consistently off by several minutes when you power up again, you probably have a bad battery (search: computer clock/CMOS batter*), and should check your OEM site for more information. Replacing a battery yourself should be a cheap solution.

Official US Time NIST -- National Institute of Standards and Technology, and USNO -- US Naval Observatory Time & Frequency Division, NIST (Boulder, Colorado) Time, Set Your Computer Clock Via the Internet, NIST Network Time Service (NTS) -- nistime-32bit.exe.lnk, http://www.boulder.nist.gov/timefreq/service/its.htm

See the Public Domain NIST Software area for downloadable synchronization software. Then if you want to set up with automatic synchronization, choose an NIST server near you then to have the time synchronize when you start up your machine add once within the Target box in the properties window of the shortcut in the \Windows\Start Menu\Programs\Startup folder: i.e. C:\Internet\Nisttime\nistime-32bit.exe once I tried automatic synchronization originally, but did not like it, probably useful if you have an always online connection through a cable, but I prefer to see what the difference actually is, so I run the program myself each day. Program uses sampling to improve accuracy. If the time gets way out every day, you will probably have to replace a small battery in your computer. What Time Is It? (US Navy) Another Realtime Clock (US Navy) International Time zones MS KB Q262680, List of Simple Network Time Protocol Time Servers on the Internet Outside of the US http://www.arachnoid.com/abouttime/index.html excellent synchronization. GMT - Greenwich Mean Time, Universal World Time -http://greenwich2000.com/ Greenwich 2000 Home Page -- http://greenwich2000.com/ World Time -- http://www.worldtime.com/cgi-bin/wt.cgi World Time Server anywhere, anytime -http://www.worldtimeserver.com/ -- get the Atomic Clock synchronization, perhaps questionable lots of adverts. Some Date/Time Tables or Calculators Daylight Savings Time, Dates for Change, in the US. How to get local time based on the GMT or GPS time, GPS units typically report Universal Time (GMT time zone). Calculators: sunrise/sunset, Solar Position Calculator

Clocks including in the System Tray and related downloads (#clocks)


Alarm Clock, Turn your $3,000 computer into a $30 Alarm Clock. Karen Kenworthy, writer for former Windows Magazine, writing their Power Users column. [LG] Clock.exe is supplied with Windows NT, and shows time hh:mm:ss and the date (but not day of the week). Can be resized for a small display or even a full screen display. Black text or outlined text on gray background. Choice of local time or GMT, and can be displayed without title bar. TClockEx, Taskbar Clock Enhancer v1.4.2 , Dale Nurden. http://www.rcis.co.za/dale/tclockex/index.htm, to see seconds, date and more in tray clock, CPU% not displaying on Win2000. Mouse over shows 16KB RAM avail 87% memory load, Fri 02/11/2000 (42/365) CPU xx% your customized mini summary, mouse-click a calendar, right-click more options. Display of time and/or date of your choice and colors on taskbar. (originally seen in zdnet hotfree downloads) Title Bar Clock, v1.4 [62k] W9x/2k/XP FREE, {PC clock} TBC displays the day, month, time, and megabytes of free physical memory in the right side of the Title Bar of the main window Something frequently asked in newsgroups is how to place a clock into an Excel spreadsheet, something you should not do as it will severly affect/curtail your Excel usage. (see #clock).

Date Information, for those who are serious or just interested (#dateinfo)
Information Please: Today in History, Events that happened on this date in history, world, US news, current events today calendar timeline. [chronology, almanacs, Homework Center]

Mostly Useless but Interesting Information (#interesting)


The Julian and Gregorian Calendars Quarters, how year is divided into quarters: English (seasonal), Scots(different seasonal), US (tax). What time is it? VCR Clock Time | geekBlue.net, You'll find a link basically to the most annoying image in the world.

Examples
Calendar Control in Excel, Using, Microsoft article. Date Calculation Worksheet Examples. Some additional date information can be found in used in footers.

=GetFormula(cell) can be used to show formula in use as seen in the examples on this page. Working with dates, one frequently ends up with validly formatted dates appearing as text. Reentering each of the dates will change them from text to dates. F2 then Enter is faster, still better is to use a macro to accomplish this. See ReEnter() macro. Related Information ON/OFF site

Related Information (#related)


Related Information on Other Sites
My DATETIME page appears to have concentrated on formatting dates and times, while Chip Pearson appears to have concentrated more on calculations in his DATETIME pages. Nothing remains static on web pages so you may want to recheck pages from time to time. I also have a Date Calculation page which shows sample calculations in a simulated spreadsheet as a companion to this page. DATETIME one of Chip Pearsons Excel Pages Chips site contains a series of how tos and macros for dates and times. Additional macros and how tos can be found in holidays. Another of Chips pages Date And Time Entry for XL97 describes how to enter time or dates without separators -- i.e. 1234 for time entry 12:34. Third Friday of the Month and additional Worksheet Functions For Dates And Times similar to 4th Monday of a month (above). Scheduling Procedures With OnTime Date and Time [Excel] at The Access Web -- Dev Ashish Time and Date, A guide to time zones, calendars (by Country), sunrise/sunset, dates on/off daylight savings time. World Clock and Configure your own cities for time checking. Since Excel will not accept dates before 1900, DATEDIF() will not work for dates before 1900. As previously mentioned John Walkenbach has created as an addin to handle years 0100-9999 in his Extended Date Functions Add-In, which requires at least XL97. http://www.j-walk.com/ss/excel/files/xdate.htm and also on Johns site is Spreadsheet History. Also see XL: Excel Incorrectly Assumes 1900 Is a Leap Year -- The actual treatment of dates in Johns XDATE functions is that of VBA, which is better than the treatment found in Excel. Also of interest A downloadable employee time sheet can be found in John Walkenbachs http://www.j-walk.com/ss/excel/files/index.htm Obtaining and Changing a Files Created, Accessed and Modified Dates at Randy Birchs VBnet (Visual Basic File API Routines) -- this page tells how to obtain/change a file's created, last access, and last modified dates. Identifies five different times (System Time, Filetime, local systemtime or filetime, MS-DOS, Windows). For instance Filetime is stored as 100-nanosecond intervals since Jan 1, 1601. (does not

specifically relate to Excel). This example allows you to change the stored times. (functions: GetFileDateString, GetSystemDateString) Calendars, <B662658A.1A7%[email protected]> site is http://www.altcal.com/ also see Q213795 below. TimeCore Solo ~ time management for the Individual, v1.1 [4.0M] W9x/2k/XP FREE (not Excel), {Time management} TimeCore Solo is a time tracking program with a recording engine that captures time worked on a task or project. [LockerGnome]

Related newsgroup postings


Calendar control added for entry into active cell from a Calendar, Chip Pearson, 2002-02-24, misc.

Microsoft Knowledge Data Base (MS KB)


Useful search argument in Excel For Windows area: xl

date and xl and time and

KB72578 XL: Converting Hours in Decimal Form to HH:MM:SS Format KB81026 XL: Calculating Days Remaining in a Time Period KB81694 XL: Formula to Calculate Number of Days in Month KB94870 XL: Changing the Date or Time Format in a Header or Footer KB99349 XL: Working with Time Periods That Exceed 24 Hours KB112361 XL: Negative Date/Time Value Displayed as Pound Signs (###) KB129277 XL: Undocumented Worksheet Function DATEDIF (see note earlier about removal from MS KB or see Chip Pearsons page for information pertaining to the missing KB129277 - datedif) KB151503 XL: How to Call a Macro Repeatedly on a Fixed Time Interval KB161607 XL97: Macro to Change the Date/Time Format in a Header/Footer KB164406 XL: How Microsoft Excel Works with Two-Digit Year Numbers. KB181370 XL: Microsoft Excel Incorrectly Assumes 1900 Is a Leap Year KB183626 XL: How the DateSerial Function Works with Year Arguments KB116281 XL: Visual Basic Procedures for Julian Date Calculations KB168435 XL: Maximum Times in Microsoft Excel, (10,000 in XL95 and later) KB213795 XL2000: How to Create a Monthly Calendar. Also see 2002 Excel Calendar (in Template Gallery) KB214330 XL: Description of the differences between the 1900 date system and the 1904 date system in Excel, This article describes the two date systems and the problems that you may encounter when you use workbooks that use different date systems KB214094 XL: HOW TO: Use Dates and Times in Excel 2000 KB214391 XL2000: How Microsoft Excel Works with Two-Digit Year Numbers KB287027 XL2002: Web Query Converts Numbers That Contain Hyphens into Dates. solution: Excel 2002 provides a long needed option to Disable date recognition when importing data. KB812385 - XL2002: Cells Automatically Format with Hijri Date Format When You Type a- Before a Number.

This page was introduced on June 19, 1998.

(last update: Tue, 23 Aug 2005 01:57:38 GMT)

[My Excel Pages -- home] [INDEX to my site and the off-site pages I reference] [Site Search -- Excel] [Go Back] [Return to TOP]
Please send your comments concerning this web page to: David McRitchie send email comments

Copyright 1997 - 2004, F. David McRitchie, All Rights Reserved

Date & Time


Location: http://www.mvps.org/dmcritchie/excel/datetime.htm Home page: http://www.mvps.org/dmcritchie/excel/excel.htm [View without Frames]
[y2k], [formatting], [intocell], [now], [datefmt], [vba], [addk], [days], [counting], [filter], [add], [thrumidnight], [military], [vbadates], [fixmmddyyyy], [totbymonth], [text2dates], [age], [daysinmonth], [firstdate], [mondaystart], [julian], [filldates], [ordinal], [lastsaved], [sheetwithdates], [weeknumber], [ws], [timediff], [subtracttime], [rndqtrhr], [fees], [core], [date123], [entryprob], [countdowny2k], [vbadate], [isdate], [MakeTrueDate], [t2cols], [adjust], [debug], [bus], [coverage], [clock], [timers], [StopWatchcontd], [vbaformat], [gwash], [timeinfo], [clocks], [dateinfo], [interesting], [related] [An example of a countdown timer for date was removed from this area that relied on Microsoft Virtual Machine, Microsoft Virtual Machine is no longer supported, you should install JAVA to run JAVA applets. ]

Something you should have changed before 2000 (#y2k)


There is enough confusion between US and UK dates without dealing with 2-digit years. Suggest you make changes such as the following so that all of your dates will display as four digit years. If you do not do this you may not be able to distinguish which part of the date is the year, the month, day; and have further difficulty knowing whether you actually have a 19xx year or a 20xx year. Excel will keep track of dates but it may not be what you see displayed or you may not be sure. Change your Regional Settings (shown with US values month/day/year) Short date: mm/dd/yyyy will show 12/28/1999 Long date: mmmm dd, yyyy

will show December 28, 1999 note this will change all of MS Office In Excel under Format --> cells --> Custom -->> mm/dd/yyyy see HELP for more information. The same letter combinations are used in Regional Settings as seen in Excel Help The short date format in Regional settings is used by Excel for the General format. The long date format in Regional settings is used by Excel for the Headings and Footings under page setup. Differences in Regional Settings may not be immediate apparent. Time in the US like =TEXT(A1,"[hh]:mm") might be =TEXT(A1,"[TT}:mm") in another language, incorrect use results in a #VALUE! error. Within double quotes such formulas may not translate in an exchange of workbooks (??). When Excel has recognized through some means that you have a date -entered as a date or assigned by a formula based on a cell that had a date, the short date form from your Windows Regional Settings will be used if your cell format is General. You can override the default formatting by specifically formatting a the column, for instance, with the date format of your choice.

Date and Time Formatting

(#formatting)

Additional information on Formatting Numbers, Dates, and Times in general can be found in the HELP topic About number format codes for dates and times. You will find that your Excel HELP is equivalent to the Excel XP pages referred to above, and you should be familiar with the HELP. I have some examples for numeric formats on my formula= page. For January: ; mmmm shows January, mmm shows Jan, mm shows 01, and m shows 1. Similar for d, dd, ddd, dddd which would show as 3, 03, Thu, Thursday for Jan 3, 2002. To format hours so that they dont roll over into days format as [h]:mm or as [hh]:mm An interesting format was pointed out by Dave Peterson where mm/dd/yyyy* dddd, places the date left justified (US format) and the day spelled out and right justified within the cell as ||11/14/2001 Wednesday||. It is typical number formatting but interesting applied to dates.

System Date/Time into a Cell or within Code (#intocell)


Placing a current date, or time, or timestamp constant that will not change later

Ctrl+; date Ctrl+: time Ctrl+: (space) Ctrl+; date with time ActiveCell.Value = Date ActiveCell.Value = Time ActiveCell.Value = Now ActiveCell.Value = Timer

(ctrl+semicolon) (ctrl+shift+colon) (ctrl+shift+semicolon)(space)(ctrl+Shift+colon) Equivalent usage in a macro for Date Equivalent usage in a macro for Time Returns current date and time in a macro Returns seconds since midnight in a macro (timing usages)

Additional Date/Time related shortcuts Ctrl+Shift+# Ctrl+Shift+@ Apply the Date format with the day, month, and year Apply the Time format with the hour and minute, and indicate A.M. or P.M.

Placing a current date or time that will update on recalculation (#now)


The use of NOW() will place the system date and time into the cell The format is dependent on your date and time settings (International settings). =NOW() date & time =Now() show date if formatted for date =Now() show time if formatted for time =int(Now()) date only, must be formatted for date =mod(Now(),1) time only, must be formatted for time See "Number format codes for dates and times" in help. example of time format: hh:mm:ss examples of date or custom date format: mm/dd/yyyy and dddd mmmm dd, yyyy

Formatting for Date and Time (#datefmt)


Formatting is done using Format --> cells --> date or custom Help --> Find --> formats --> Custom number formats --> For more information about number format codes for dates and times, click [>>]

Entering Dates into a Cell Formatted as General


Entering a month and day, or a month and year will cause the formatting to change for a General Cell. This can also produce problems if the figure entered is actually a fraction and not a date. (partial solution)
Generate s Format

Entered as:

Displays As

Actual value

Actual Date (US)

3/31

31-Mar

d-mmm

36,616.00 03/31/2000

3/32 3/31/2000 03/31/2000 3/0 3

Mar-32 mmm-yy 03/31/2000 m/d/yy 03/31/2000 m/d/yy Mar-00 mmm-yy 3 General General

11,749.00 36,616.00 36,616.00 36,586.00 3.00 -

03/01/1932 03/31/2000 03/31/2000 03/01/2000 01/03/1900

Date and Time serials


Serial for date only has no decimal places. Serial for date and time has date serial plus the time component as a fraction of a day. Serial for time is a fractional day. One hour is 1/24 day, or approximately 0.4166667 of a day as a decimal number. Formula -- =GetFormula(cell) datestamp date serial =NOW() 6/19/98 7:25 35965.31 =0.01 1/0/00 12:14 AM 0.01 =0.51 1/0/00 12:14 0.51 =10 1/10/00 0:00 10.00 =INT(NOW()) 6/19/98 0:00 35965 =MOD(NOW(),1) 1/0/00 7:25 0.309130787 =DATEVALUE(TEXT(NOW(), "mm/dd/yy")) 06/19/1998 35965.00 =DATE(NOW(), 1,1) 01/01/1998 35796.00 =DATE(year(now()),month(now())+1,0) (end of current month) 06/30/1998 35976.00 =DATE(year(now()),month(now())+1,1) 07/01/1998 35977.00 Date entered in Excel 95 Date formatted See additional information below mm/dd/yyyy date serial 1/0/00 01/01/2000 36526 1/0/19 01/01/2019 43466 1/0/20 01/01/1920 7306 The timestamp shown is dependent on cell formatting. Normally a date would appear without a zero time, and a time would appear without a zero date. In XL95 the windowing for 2 digit dates (date window) is 00-19 represents 2000-2019, and 20-99 represents 1920-1999. The windowing dates change with later versions of Excel. XL97 and XL98(Mac) use 00-29 and 30-99.

Last Day of Current Month

Worksheet Function: -- end of Current Month =DATE(year(now()),month(now())+1,0) Programming: end of current month: (NOW is a datetime serial and has both components) ActiveCell.Value = DateSerial(Year(Now), Month(Now) + 1, 0) ActiveCell.NumberFormat = "DDD MM/DD/YYYY" You would actually format the entire column for best usage, without formatting in code. To assign a variable Dim MyDate as Date ActiveCell.Value = DateSerial(Year(Now), Month(Now) + 1, 0)

VBA Examples for Date and TIME (#vba)*


Sub ss1() 'As constants the following will not update [a1] = Int(Now) 'date [a2] = Now 'date and time [a3] = Date 'date [a4] = Date + Time 'same as now 'As Worksheet Functions the following will update [a5] = "=Today()" 'current date into worksheet formula [a6] = "=now()" 'current date [a7] = "=now() - Today()" 'current time when recalculated [a7].NumberFormat = "hh:mm" [a8] = "=MOD(NOW(),1)" 'current time when recalculated [a8].NumberFormat = "hh:mm" End Sub

Comparison of VBA and Worksheet Functions (#comparison)


While col A may have started out as format General, Excel and VBA will change the formatting from General. VBA time and now in VBA will truncate seconds, so you see 06.98 secons from Excel NOW() and 07.00 from the Excel TIME, and 06.00 seconds from VBA. Due to the truncation of seconds, VBA is not going to match your system clock. VBA Excel now() will include fractional seconds. If you want something for timing fractional seconds see Simple Timer on my Slow Response page used to time code to thousandths of a second. I have yyyymm-dd as my date in Regional Settings and hh:mm for my time (not hh:mm A/P). Format as Format as General hh:mm:ss.00 2005-04-20 09:10 09:10:06.00 2005-04-20 00:00:00.00 2005-04-20 00:00:00.00 2005-04-20 09:10 09:10:06.00 Format as Format as Formula or constant =personal.xls!GetFormula(An) 38462.3820138889 38462 38462 38462.3820138889 Formula or constant VBA coding [a2] = Now 'date and time [a3] = Int(Now) 'date [a4] = Date 'date [a5] = Date + Time 'same as now VBA coding

General hh:mm:ss.00 =personal.xls!GetFormula(An) 1900-01-00 09:10 09:10:06.98 =MOD(NOW(),1) [a8] = "=MOD(NOW(),1)" =TIME(HOUR(NOW()),MINUTE( [A9] = "=TIME(HOUR(NOW()), 09:10 AM 09:10:07.00 NOW()),SECOND(NOW())) MINUTE(NOW()),SECOND(NOW()))" 2005-04-20 09:10 09:10:06.00 38462.3820138889 [a10] = Now 'date and time (timestamp) 09:10:06 AM 09:10:06.00 0.382013888888889 [a11] = Time 'time

Adding an interval to a date (VBA code) (#addk)


Adding one month to the 31st in a calendar month can present a problem in interpretation. Here is one solution: To add one month to a date (i.e. 01/28/2001 through 01/31/2001 becomes 02/28/2001) x = DateAdd("m", 1, x - 1)
'yyyy Year, q Quarter, m Month, y Day of year, d Day, w Weekday, ww Week, h Hour, n Minute, s Second

Time is recorded in Days (#days)


Dates and times are both recorded in units of days and the actual number may be referred to as a dateserial or a timeserial. They can be entered in VBA as dateserial(year,month,day) and with timeserial(hour,minute,second). As worksheet functions you would use =DATE(year,month,day) and =TIME(hours,minutes,seconds) You can add the two to get a datetimeserial. Time is recorded in days, so 1 hour = 1/24 day = .0417 day (approx); 1 minute = 1/(24*60) = .000694 days (approx); 1 second = 1/(24*60*60) = . 00001157 days (approx) Assuming that you actually have minutes and seconds multiply by 1440 and format as a number with 2 digits. If on the other hand you really entered as hours and minutes multiply by 24 and format as a number with 2 digits. A display display Days days hours minutes seconds C 0:01:15 0.000868055555555556 1/0/00 12:00 AM =B1 0.00087 =B1 0.000868056 =B1 0.020833333 =B1*24 1.25 =B1*24*60 75.00 =B1*24*60*60 B

1 2 3 4 5 6 7 8

9 10 11 12 13 14 15

display display Days days hours minutes seconds

1:15:00 1/0/00 12:00 AM 0.05208 0.052083333 1.25 75 4500.00

0.0520833333333333 =B9 =B9 =B9 =B9*24 =B9*24*60 =B9*24*60*60

Example: Since 2:15 (2 hours 15 minutes = 0.093750 days) is stored as a fractional day you must multiply by 24 to get 2.25 hours. Suppose you record units in B1 over time in B2 as in transmitting 8 million bytes in 8 minutes, you would put 8000000 in B1 and 0:8:00 in B2. Example: B C D =GetFormula(cell) 1 Bytes 8,000,000 400,000,000 8000000 2 minutes 0:08:00 0:08:00 0.00555555555555556 3 datetimeserial 0.005555556 0.005555556 =B2 4 5 bytes/day 1,440,000,000 72,000,000,000 =B1/(B2) 6 bytes/hour 60,000,000 3,000,000,000 =B1/(B2*24) 7 bytes/min 1,000,000 50,000,000 =B1/(B2*24*60) 8 bytes/sec 16,666.67 833,333.33 =B1/(B2*24*60*60) This is just an example and bears no relationship to any actual transmissions times. A

Date Intervals, Counting (#counting)


A B C

1 12/04/1952 Count of dates within December of any year 2 12/01/1999 6 =SUMPRODUCT(N(MONTH(A1:A20)=12)) 3 11/16/2000 4 11/30/2000 Count of dates found within December, 2000 5 12/01/2000 4 =SUMPRODUCT((MONTH(A1:A20)=12)*(YEAR(A1:A20)=2000)) 6 12/05/2000 7 12/15/2000 Count of dates found between Nov 16, 2000 and Dec 15, 2000 8 12/31/2000 5 =SUMPRODUCT(N(A1:A20>DATE(2000,11,15))*N(A1:A20<=DATE(2000,12,15))) 9 5 =countif(A1:A20,">=11/16/2000")-countif(A1:A20,">12/15/2000")

10 11 02/05/2002 Count of Tuesdays between two dates (i.e. Tue Feb 5, 2002 to Tue Feb 12, 2002) 12 02/12/2002 2 =INT((A12-A11)/7)+IF(WEEKDAY(A11+4)+MOD(A12-A1,7)>=7,1) The first two formulas are based on 2000-11-20 George Simms reply in misc and the third reworked from the first. Cells A9:A20 are BLANK. Note #VALUE! would result if any cell in range was otherwise not numeric. For more information on SUMPRODUCT see Excel HELP. The penultimate solution using COUNTIF was posted by Tom Ogilvy 2000-11-21. The last solution was posted by George Simms 2000-02-19 Date in advanced filter (#filter) "<"&TODAY() -- see Sum Data for references to Advanced Filter.

Adding six months to a date (#add)


Adding six months to a date may have different interpretations. For instance what is six months from a date if the month six months later does not have the same number of days. (see Norman Harker link below)

A B C 1 08/15/2000 02/15/2001 =DATE(YEAR(A1),MONTH(A1)+6,DAY(A1)) 2 08/31/2000 03/03/2001 =DATE(YEAR(A2),MONTH(A2)+6,DAY(A2)) 3 4 08/15/2000 02/11/2001 =A4 + 180 5 08/31/2000 02/27/2001 =A5 + 180 6 7 08/15/2000 02/13/2001 =A7 + 365/2 8 08/31/2000 03/01/2001 =A8 + 365/2 9 10 08/15/2000 02/28/2001 =DATE(YEAR(A10),Month(A10)+7,0) 11 08/31/2000 02/28/2001 =DATE(YEAR(A11),Month(A11)+7,0) 12 13 08/15/2000 02/15/2001 =IF(DAY(DATE(YEAR(A13),MONTH(A13)+6,DAY(A13)))<>DAY(A13),DATE(Y 14 08/31/2000 02/28/2001 =IF(DAY(DATE(YEAR(A14),MONTH(A14)+6,DAY(A14)))<>DAY(A14),DATE(Y A shorter solution than seen in the last two rows adding 6 months is a solution attributed to Chip Pearson as described in a posting (as a tutorial) by Norman Harker (2002-10-13) in worksheet functions adding one month, you can add one month to a Jan 31st date for your own test. =DATE(YEAR(F2),MONTH(F2)+1,MIN(DAY(F2),DAY(DATE(YEAR(F2),MONTH(F2 )+2,0))))

Also See use of DATEDIF on this page, and explanation of DATEDIF Worksheet Function on one of Chip Pearson's pages. Not to be confused with dissimilar DATEDIFF VBA function.

Time Sheets, providing for start and end time through midnight (#thrumidnight)
Time is recorded as fractional days, so 24 hours = 1 day. The following logical formula tests start time (A1) against end time (B1) and adds 1 if A1 is greater than B1. If A1>B1 a true condition exists, value 1 (1=24 hours); otherwise, a false condition exists, value 0
=(A1>B1)+B1-A1 'End time - start time

A more complete example follows that includes break time. A 2 3 4 5 6 7 23:15 0:00 0:00 7:45 8:30 =(A7>B7)+B7-A7+(C7>D7)+D7-C7 John Walkenbach has sample time sheets on his site see Related areas at end of this web page. format of format of E1 E2 23:15 B 3:15 C 4:00 D 7:45 E F

1 START start.break end-break STOP Worked 7:45 =(A2>B2)+B2-A2+(C2>D2)+D2-C2 7.75 =E2*24 h:mm _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)

Entry of Military Time without separations (#military)


The following formula was posted by Glenn Schwandt 1999-11-24 in worksheet.functions utilizing a round down to eliminate right two digits, and a MOD to get the remainder of a divide by 100. A TIME 1 2 3 1200 1201 2400 3359 B C Time =getformula(Bx) 0:01:00 =ROUNDDOWN(A2,-2) / 2400 + MOD(A2,100) / 1440 0:02:00 =ROUNDDOWN(A3,-2) / 2400 + MOD(A3,100) / 1440 0:03:00 =ROUNDDOWN(A4,-2) / 2400 + MOD(A4,100) / 1440 12:00:00 =ROUNDDOWN(A5,-2) / 2400 + MOD(A5,100) / 1440 12:01:00 =ROUNDDOWN(A6,-2) / 2400 + MOD(A6,100) / 1440 0:00:00 =ROUNDDOWN(A7,-2) / 2400 + MOD(A7,100) / 1440 9:59:00 =ROUNDDOWN(A8,-2) / 2400 + MOD(A8,100) / 1440

1 2 3 4 5 6 7 8

Convert to or from Date Serial as Text Constants (#vbadates)


Note the use of Format(cell.Value, "Short Date") which will use your Regional Settings to format the short date.
Sub ConvertFromDateSerial() 'Convert from dateserial to formatted date text constant 'For Excel dateserials on/after March 1, 1900 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range On Error Resume Next '-- in case no cells selected For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlCellTypeConstants)) cell.Value = Format(cell.Value, "Short Date") 'see help for "Named Date/Time Formats (Format Function)" Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub Sub ConvertToDateSerial() 'Convert from recognizable US date to date serial 'For dates on/after March 1, 1900 back to dateserial Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range On Error Resume Next '-- in case no cells selected For Each cell In Intersect(Selection, _ Selection.SpecialCells(xlCellTypeConstants)) cell.Value = Int(DateValue(cell.Value)) cell.NumberFormat = "general" Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub

Fixup for Dates and Times entered as Text (#fixmmddyyyy)


Assistance to Install a Macro or User Defined Function on my Formula page. Dates are in cells as mmddyyyy and time are hhmm, need to correct these text entries '01312000 to 01/31/2000 and '0136 to 01:36 =DATE(right(a1,4),left(a1,2),mid(a1,3,2) =TIME(left(b1,2),right(b1,2))
Sub Fixmmddyyyy() Dim cell As Range Selection.NumberFormat = "mm/dd/yyyy" On Error Resume Next For Each cell In Selection If Len(cell) = 8 Then cell.Value = DateSerial(Right _ (cell.Value, 4), Left(cell.Value, _ 2), Mid(cell.Value, 3, 2)) End If Next cell Sub Fixhhmm() Dim cell As Range Selection.NumberFormat = "hh:mm" On Error Resume Next For Each cell In Selection If Len(cell) = 4 Then cell.Value = TimeSerial(Left(cell.Value, 2), _ Right(cell.Value, 2), 0) End If Next cell End Sub

End Sub Sub FixhhmmV() Sub fixhhmmss() Dim cell As Range 'posted as fixtime6(), fix mmss, hmmss, Dim vValue As Single hhmmss On Error Resume Next 'DMcRitchie, programming 2001-03-22 For Each cell In Selection Dim x6 As String If InStr(1, cell.NumberFormat,":") = 0 Then Dim cell As Range If cell.Value > 1 Then 'Not a time serial For Each cell In Selection.SpecialCells( _ yet xlCellTypeConstants, xlNumbers) cell.Value = TimeSerial(Int(cell.Value / If cell >= 1 Then 100), _ x6 = Right(Format(cell.Value, "000000"), Int(cell.Value - 100 * Int(cell.Value / 6) 100)), 0) cell.Value = TimeSerial(Left(x6, 2), _ End If Mid(x6, 3, 2), Right(x6, 2)) End If 'cell.NumberFormat = "hh:mm:ss" Next cell End If Selection.NumberFormat = "[hh]:mm" Next cell End Sub End Sub

To change entry at time of entry, Chip Pearson has Date And Time Entry for XL97 and up to enter time or dates without separators -- i.e. 1234 for time entry 12:34.

Using an Array Formula to total by Month (#totbymonth)


A 1 Name 2 Bart 4 Chris 5 Leslie 6 Pat 7 Toby 8 9 Feb 10 Feb Invite Birthdates 7 2 {=SUM((C2:C7)*(MONTH(B2:B7)=2))} {=SUM(1*(MONTH(B2:B7)=2))} B 03/12/1984 02/02/1980 12/25/1975 08/29/1986 02/14/1983 C 3 2 4 1 6 3 The array formula is entered with Ctrl-Shift-Enter do not enter the braces. Read more about Array Formulas on Chip Pearson's site. D

Birthdate Friends Formula

3 Bobby 11/02/1985

A couple more Array formulas, find where is next to 1 or is it 1


=SUMPRODUCT((E3:E24="a")*(F3:F24=1)) enter as array formulas =SUMPRODUCT((E3:E24="a")*(F3:F24="1")) Ctrl+Shift+Enter

Converting Text Dates to Dates (#text2dates)


Either of these methods will create a date serial from the date not dissimilar from how your system is setup. The formatting in the resulting cells will display the date format desired. Now would be a good time to start using four digit dates if you arent already.

1. Use Worksheet Function =Datevalue(text) will convert most anything if the date is in the same format as your system is set up, or 2. Create the dateserial by placing a 1 in a cell on spreadsheet, copy it (Ctrl+C) and then select the column or whatever of text dates and use Paste Special feature with Multiply. Now what to do if the dates are not in the same format as your system. UK text dates (i.e. dd/mm/yy) coming in on a US/Canada system (i.e. mm/dd/yy) to be formatted for US/Canada. You may have to use MID and worksheet function =DATE(year,month,day).

Converting Dates to Text (Dates2Text)


To get a date into text so that it can be left justified and span columns.
=TEXT(NOW(),"mmmm dd, yyyy")

Age in Years, Months, Days using DATEDIF Worksheet Function (#age) (#datedif)
The following shows age in Years + Months + Days A B 1 03/27/1989 3/27/89 2 05/09/1998 =TODAY() same as INT(NOW()) 3 9 =DATEDIF(A1,A2,"y") age in years 4 1 =DATEDIF(A1,A2,"YM") plus months 5 12 =DATEDIF(A1,A2,"md") plus days 6 Calculate number of days to next birthday 7 322 =DATE(YEAR(A1)+A3+1,MONTH(A1), DAY(A1))-A2 Column B shows formula used in Column A, =GetFormula(cell) MS DB KB129277 XL: Undocumented Worksheet Function DATEDIF (** See Next paragraph**) Microsoft has removed DATEDIF from their knowledge database ( thread). Chip Pearson maintains DATEDIF information on his site. In XL95 you must use the Analysis Toolpak add-in. The DATEDIF() worksheet function apparently comes with XL97 and is officially included in XL2000 and documented in the XL2000 help file (you can see here -- xlfctDATEDIF.htm). Later versions of Excel dropped DATEDIF from the help file. When thinking of DATEDIF there is a tendency to forget that the difference between two dates in days is a simple subtraction. KB216578 indicates that DATEDIF is not supported in the Office Worksheet Component meaning it is not available in interactive HTML created from Excel 2000.

Counting Years, Months and Days similar using VBA DATEDIFF to return a three cell array. Tip 55 - John Walkenbach - also gives an idea of what an array formula is and how to implement. KB149689 XL: Visual Basic Macro Examples for Working With Arrays. If you have XL97 or later suggest dumping DATEDIF for John Walkenbachs XDATEDIF Extended Date Functions Add-In, eliminating problems with negative dates involving subtraction in MS date system and incorrect leap years in older MS 1900 date system. (also dates prior to 1900 below). Using DATEDIF in a program The following was posted by Chip Pearson on 6Dec1999 and probably can be found on his site.
Function Age(TheDate As Double) As String Age = _ CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""y"")")) & " years " & _ CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""ym"")")) & " months " & _ CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""md"")")) & " days" End Function

Harlan Grove posted an interesting formula that does not require DATEDIFF to yield age: =YEAR(TODAY()-birthdate)-YEAR(0)

Number of days in a Month (#daysinmonth)


Refer to KB81694 XL: Formula to Calculate Number of Days in Month Examples below for Jul 14, 1998 (07/14/1998) =DAY(DATE(YEAR(The_Date),MONTH(The_Date)+1,0)) 31 =DAY(DATE(YEAR("07/14/1998"),MONTH("07/14/1998")+1,0)) =DAY(DATE(my_year,my_month+1,1)-1) 31 =DAY(DATE(1998,7+1,1)-1)

First, Last, Nearest, Closest, nth weekday (4th Monday) in Month, Date calculations (#firstdate)
WEEKDAY Worksheet Function (1=Sun, 2=Mon, 3=Tues, 4=Wed, 5=Thur, 6=Fri, 7=Saturday) First Monday of Month (day of month 1-7): 1 + correction Third Monday of Month (day of month 15-21): 15 + correction (Dates are shown in US/Canada format mm/dd/yyyy) 04/14/2001 7 Sat 36995 First Day of Week 04/08/2001 1 Sun =B1-WEEKDAY(B1)+1 Last Day of Week 04/14/2001 7 Sat =B1-WEEKDAY(B1)+7 First Day of Month 04/01/2001 1 Sun =DATE(YEAR(B1),MONTH(B1),1)

Last Day of Month First Day of Year Last Day of Year Closest Monday Next Monday Next Monday 1st Monday of Month 2nd Monday of Month 3rd Monday of Month 4th Monday of Month 5th Monday of Month

04/30/2001 2 Mon =DATE(YEAR(B1),MONTH(B1)+1,0) 04/01/2001 1 Sun =DATE(YEAR(B1),MONTH(B1),1) 12/31/2001 2 Mon =DATE(YEAR(B1)+1,1,0) 04/16/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),DAY(B1)+CHOOSE(WEEKDAY(B1),1,0 04/16/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),DAY(B1)+CHOOSE(WEEKDAY(B1),1,7 04/16/2001 2 Mon =A1-WEEKDAY(A1,2)+8 04/02/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),CHOOSE(WEEKDAY(DATE(YEAR(B1) 04/09/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),7+CHOOSE(WEEKDAY(DATE(YEAR(B 04/16/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),14+CHOOSE(WEEKDAY(DATE(YEAR( 04/23/2001 2 Mon =DATE(YEAR(B1),MONTH(B1),21+CHOOSE(WEEKDAY(DATE(YEAR( 04/30/2001 2 Mon =IF(MONTH(DATE(YEAR(B1),MONTH(B1),28+ CHOOSE(WEEKDAY(DATE(YEAR(B
MONTH(B1),1)),2,1,7,6,5,4,3)))=MONTH(B1), DATE(YEAR(B1),MONTH(B1), 28+CHOOSE( WEEDATE(YEAR(B1),MONTH(B1),1)),2,1,7,6,5,4,3)),"none")

3rd Wed. of Month 04/30/2001 4 Wed =A1-DAY(B1)+22-WEEKDAY(B1-DAY(A1)+4) -- Daniel M. Last Monday of Month 04/30/2001 2 Mon =DATE(YEAR($B$1),MONTH($B$1)+1,1)-WEEKDAY(DATE(YEAR($B$
see Date Calculations

Previous Monday 04/09/01 2 Mon =B1-CHOOSE(WEEKDAY(B1,1),6,7,1,2,3,4,5) For a different day of the week rotate the 2nd to last parameters in CHOOSE. i.e. 7,6,5,4,3,2,1 for Wednesday instead of 2,1,7,6,5,4,3 for Monday as used in some of the formulae. Formula in C1 & D1, downward =IF(ISNUMBER(B1),WEEKDAY(B1),"") Formula in E1, downward =personal.xls!getformula(E1) see documentation for this User Defined Funct Weekday(date,1) week starts on Sunday (US default) Numbers 1 (Sunday) through 7 (Saturday). Weekday(date,2) week starts on Monday Numbers 1 (Monday) through 7 (Sunday). Additional formulae and formulae with similar purpose can be found on my Date Calculations page.

Monday week starting dates (#mondaystart)


Week beginning on Monday, will assume Sunday belongs to the previous week of. Format column B as mm/dd/yyyy and column C as ddd. Column C should only show Mon. A2: =TODAY() B2: =A2-MOD(A2-2,7) C2: =B2 programming. format column as mm/dd/yyyy Function Mon_Start(sdate As Date) As Date Mon_Start = sdate - (sdate - 2) Mod 7 End Function

Julian dates, in worksheet (#julian)


Works for numbers or text in the form yyddd, where yy is the year and ddd is the day within year. i.e. 98003, 99003, 00003, 3, 01003, 1003.
=DATE(IF(INT(A1)>39000,INT(A1/1000)+2000,INT(A1/1000)),1,MOD(A1,1000))

These are, of course, the IBM computing Julian dates. The real Julian dates are another matter they begin January 1, 4713 BCE (on the old Julian calendar).

Using fill-handle with Rt-Mouse button to fill in a Calendar of weekdays (#filldates)


You can specify how you want the filling to be done if use the RtMouse button instead of the LtMouse button when you use the fill handle to drag your selection down. After dragging you will be asked what you want to do. || copy values, fill series, fill formats, fill values|| || fill days, fill weekdays, fill months|| || Linear trend, Growth Trend, series ... || with other choices where applicable. More information concerning fill-handle.

Ordinal numbers, and Ordinal numbers in dates (#ordinal)


Ordinal number, any of the numbers first, second, third, etc. (in distinction from one, two, three, etc. which are called cardinal numbers. Also ordinal numeral. 21st and other dates with numbers as 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, etc. =A2&IF(INT(MOD(A2,100)/10)=1, "th", IF(MOD(A2,10)=1, "st", IF(MOD(A2,10)=2,"nd", IF(MOD(A2,10)=3, "rd","th")))) 21st May, 1999 and other dates with days of month as 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, etc. =DAY(A2)&IF(INT(MOD(DAY(A2),100)/10)=1, "th", IF(MOD(DAY(A2),10)=1, "st", IF(MOD(DAY(A2),10)=2,"nd", IF(MOD(DAY(A2),10)=3, "rd","th"))))& " " & TEXT(A2,"mmmm, yyyy") or as a Function
Function OrdDate(arg) dd = Day(arg) mmmm = Format(arg, "mmmm") '*Corrected* yyyy = Year(arg) Select Case Day(arg) Case 1, 21, 31 OrdDate = dd & "st " & mmmm & ", " & yyyy Case 2, 22 OrdDate = dd & "nd " & mmmm & ", " & yyyy Case 3, 23 OrdDate = dd & "rd " & mmmm & ", " & yyyy Case 4 To 20, 24 To 30 OrdDate = dd & "th " & mmmm & ", " & yyyy End Select End Function

A macro by Ron Rosenfeld (see thread) changes the format rather than the text. The macro is written for XL97 and has an advantage in not using a second cell to display a text format. Written as a Worksheet_Change macro it will change the format for all dates on a particular worksheet when they are entered, changed or recalculated. The big advantage is that the cell can continue to be treated as a numeric value.

Last Saved Date (#lastsaved)


=FileDateTime(ActiveWorkbook.FullName)

Also see use in Pathname in headings, footers, and cells. Will create a documentation page someday with all the documentation items and include the following Thomas Ogilvy reference: Read a Disk Directory to into a Spreadsheet, also see properties.

Create a new worksheet with 1 weeks worth of dates (#sheetwithdates)


Create a new worksheet one week of dates down Column A. Dates created for the current week. Example run on Fri 12/29/2000. Constants for dates are generated not formulas with date functions.
Option Explicit Sub Macro39() Sheets.Add Range("1:1,A:A").Font.Bold = True Columns("A:A").Select Selection.NumberFormat = "ddd mm/dd/yyyy" Range("a2").Formula = Int(Now()) _ - Weekday(Int(Now())) + 1 Range("A2").AutoFill _ Destination:=Range("A2:A8"), _ Type:=xlFillDefault Range("a1").Formula = _ Format([a2], "mm/dd/yy") & Chr(10) _ & " - " & Format([a8], "mm/dd/yy") Columns("A:A").EntireColumn.AutoFit Range("B2").Select ActiveSheet.Name = "D." & Format([a2], _ "yyyymmdd") 'rename sheet End Sub

1 2 3 4 5 6 7 8

A B 12/24/00 - 12/30/00 Sun 12/24/2000 Mon 12/25/2000 Tue 12/26/2000 Wed 12/27/2000 Thu 12/28/2000 Fri 12/29/2000 Sat 12/30/2000

Week number -- European Style -- ISO Standard 8601 (#weeknumber)


The following formula was posted by Laurent Longre (1999-08-10), D is the date.
=INT((D-SUM(MOD(DATE(YEAR(D-MOD(D-2,7)+3),1,2),{1E+99,7})*{1,-1})+5)/7)

In Europe weeks begin on a Monday and end on Sunday, even so the formula =WEEKNUM(date,2) which indicates that weeks begin on Monday will not work for European

usage. In the US the first week begins on January 1st, so the first week and the last week of a year may both have less than 7 days. In the European style (ISO 8601) the week begins on a Monday and includes the first Thursday of the new year. The reason for Thursday is that the majority of the days in the Mon-Sun week will be in the new year. This is the same as saying the week with Jan 4th will always be the first week. For additional information see A Summary of the International Standard Date and Time Notation at http://www.cl.cam.ac.uk/~mgk25/iso-time.html which contains information on ISO 8601 and references additional material. Also see Pat McCotter's posted an article 1999->03->20. Chip Pearson has followed this more closely you can find out more about week numbers, including English postal service on Chips site.

Date & Time Worksheet Functions in Excel (#ws)


Refer to your HELP (F1)file for more information. DATE Returns the serial number of a particular date syntax: DATE(year, month, day DATEVALUE Converts a date in the form of text to a serial number Example: =DATEVALUE("8/22/55") equals 20323 DAY Converts a serial number to a day of the month DAYS360 Calculates the number of days between two dates based on a 360-day year EDATE Returns the serial number of the date that is the indicated number of months before or after the start date syntax: EDATE(start_date, months) Example: =EDATE(DATEVALUE("01/15/91"),1) equals 33284 or 02/15/91 Example: =TEXT(EDATE(DATEVALUE("January"&" 15, 1999"),1),"mmmm") equals February EOMONTH Returns the serial number of the last day of the month before or after a specified number of months HOUR Converts a serial number to an hour MINUTE Converts a serial number to a minute MONTH Converts a serial number to a month NETWORKDAYS Returns the number of whole workdays between two dates.
NETWORKDAYS(start_date,end_date,holidays) NETWORKDAYS("10/01/1998","12/01/1998","11/26/1998")

NOW SECOND TIME TIMEVALUE TODAY

Result of above is 43 (61 days between). Also see WORKDAY. Returns the serial number of the current date and time Converts a serial number to a second Returns the serial number of a particular time Converts a time in the form of text to a serial number Example: =TIMEVALUE("2:24 AM") equals 0.1 Returns the serial number of todays date

WEEKDAY

WORKDAY

Converts a serial number to a day of the week Example: =WEEKDAY("2/14/907quot;) equals 4 (Wednesday), similarly Example: =TEXT("4/16/90", "dddd") equals Monday Returns the serial number of the date before or after a specified number of workdays. This is the opposite of NETWORKDAY.
WORKDAY(start_date,days,holidays)

YEAR YEARFRAC

Converts a serial number to a year Returns the year fraction representing the number of whole days between start_date and end_date

Time Difference Calculations (#timediff)


Subtracting Time (#subtracttime)
A B C End 10:55 8:20 D E 0.00 2.58 D3: =C3-B3+(B3>C3) E3: =24*D3 F G

1 Format--> General General [h]:mm 2 Employee Start 3 Jan H. 4 Pat T. 8:20 10:55 2:35

Duration Hours =GetFormulaD(address) 21:25 21.42 D4: =C4-B4+(B4>C4) E4: =24*D4

The formula to subtract times where the ending time might look like an earlier time would be: =C3-B3+(B3>C3) The last part is a logical expression that adds 1 if start time is greater than end time, or 0 otherwise. Time is measured in days so the addition of 1 is adding 24 hours to the equation. You subtract one time from the other. The result should be formatted as time but since you might end up with more than 24 hours you would format as [h]:mm instead of h:mm

Rounding Time value to Quarter Hour (#rndqtrhr)


Remember time is stored as days, so one quarter hour is 1/(24*4) days or .01041666 days. The fraction will be more accurate. MROUND is part of the Analysis Toolpak Add-in. Rounding to nearest quarter hour: Rounding down to nearest quarter hour: Rounding Up to nearest quarter hour: Rounding Up to nearest half hour: =MROUND(A22,1/(24*4)) =FLOOR(A22,1/(24*4)) =CEILING(A22,1/(24*4)) =CEILING(A22,1/(24*2))

Consulting Fees (#fees)


C D E F G H I J

8 9 10 11 12 13

hh:mm 4:06 7:29 7:31 8:00 37:30

Rounded Billed @ HRS Rate/HR hh:mm $100/HR 4:30 4.5 7:30 7.5 8:00 8.0 8:00 8.0 37:30 37.5 100.00 100.00 100.00 100.00 $ 45.00 $ 75.00 $ 80.00 $ 80.00

Addr Formula C9 D9 E9 F9 G9 0.170833333333333 = ROUNDUP(C9*48,0)/48 = ROUNDUP(C9*48,0)/2 100 =F9 * ROUNDUP(C9*48,0)/2

100.00 $ 375.00

Wages calculation with C9 having a time in hh:mm and you want to round up at 1/2 hour intervals shown in D9. Column C is formatted as [hh]:mm =Roundup(c9*48,0)/2 =100* ROUNDUP(C9*48,0)/2 format as 0.0 for decimal hours format as dollars not a time

Time is measured in days, 24 hours in 1 day. The roundup calculation does not handle fractions so multiply 24 by 2 get the roundup and then divide by 2

Calculating hours outside of Core range (#core)


The basic concept is: number of hours before core hours + number of hours after core hours =IF(Shift_Start<Core_Start, Core_Start-Shift_Start,0) + IF(Shift_End>Core_End, Shift_End-Core_End,0) but since time is not recorded with the dates this becomes more complicated.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > -- corrections to formulas 2002-02-09 to fix errors when converted to HTML--c3: =B3-A3+(A3>B3) is equivalent to =IF(B3>A3,B3-A3,B3-A3+1) d3: =IF(B3>=A3,MAX(MIN(B3,G3)-A3,0)+MAX(B3-H3,0), MIN(B3+1,1+G3)-MAX(A3,H3)) e3: =IF(ABS(D3-F3)<0.0001,"yes","NO") f3: is the goal, it is what is to be expected from the calculations G3 is the Core.start time H3 is the Core stop time Don't know if this is a concern or not: If clock time goes through midnight and core start and stop times it will be incorrect, but your elapsed hours would exceed 16 hours as seen in my last tested values. David McRitchie (1999/08/01) Tested example: --A-- --B-- --C-- --D-- -E- --F-- --G-- --H-Start Stop Elap calc. ^^^ GOAL c.start c.ent 23:00 07:00 08:00 08:00 yes 08:00 07:00 15:00 00:00 08:00 08:00 07:00 yes 07:00 07:00 15:00 03:00 11:00 08:00 04:00 yes 04:00 07:00 15:00 12:00 20:00 08:00 05:00 yes 05:00 07:00 15:00 16:00 00:00 08:00 08:00 yes 08:00 07:00 15:00 12:00 20:00 08:00 05:00 yes 05:00 07:00 15:00 23:00 15:00 16:00 08:00 yes 08:00 07:00 15:00 00:00 16:00 16:00 08:00 yes 08:00 07:00 15:00 03:00 19:00 16:00 08:00 yes 08:00 07:00 15:00 12:00 04:00 16:00 13:00 yes 13:00 07:00 15:00

> > > > > > > > > > > > > > > > > > > > > > > > > > > > >

16:00 00:00 04:00 08:00 12:00 16:00 20:00 00:00 04:00 08:00 04:00 06:00

08:00 16:00 20:00 00:00 04:00 08:00 12:00 16:00 04:01 08:01 04:00 05:00

16:00 16:00 16:00 16:00 16:00 16:00 16:00 16:00 00:01 00:01 00:00 23:00

15:00 08:00 08:00 09:00 13:00 15:00 11:00 08:00 00:01 00:00 00:00 14:00

yes yes yes yes yes yes yes yes yes yes yes NO

15:00 07:00 15:00 08:00 07:00 15:00 08:00 07:00 15:00 09:00 07:00 15:00 13:00 07:00 15:00 15:00 07:00 15:00 11:00 07:00 15:00 08:00 07:00 15:00 00:01 07:00 15:00 00:00 07:00 15:00 00:00 07:00 15:00 15:00 07:00 15:00 == failed should be 15 hours not 14 hours.

Similar information in a little different format, basically switch usage of G & H columns. Rate ---> 1 1.5 Start End Norm. Prem. -- -Time Time Hours Hours -17:00 01:00 03:00 05:00 01:00 09:00 08:00 05:00 09:00 17:00 08:00 00:00 17:00 01:00 08:00 05:00 01:00 09:00 08:00 05:00 09:00 17:00 08:00 00:00 C3: D3: Extra paid Extra Pay hours -- From To --20:00 --20:00 --20:00 --20:00 --20:00 --20:00 hours 6:00 6:00 6:00 6:00 6:00 6:00

=B3-A3+(A3>B3)-D3 =IF(B3>=A3,MAX(MIN(B3,H3)-A3,0)+MAX(B3-G3,0), MIN(B3+1,1+H3)-MAX(A3,G3))

To show time as a hours with decimal fraction multiply Excel hours by 24.

-----The following formula was posted 2002-02-09 by Daniel Maher and fixes a problem that I indicated in the first example. This solution is for the second example. Will at least be including this until I fix my own formula. DanielM 2002-02-09 =IF(CheckOut>=CheckIn,MAX(0,MIN(CheckOut,UpperBound)A B C D E MAX(CheckIn,LowBound)),MAX(0,UpperBound-MAX(CheckIn, in out of LowBound))+MAX(0,MIN(CheckOut,UpperBound)-LowBound)) 1 IN OUT reported core core For the time OUTSIDE the boundaries 2 6:00 14:00 8:00 6:00 2:00 of [LowBound ... UpperBound], it is 3 0:00 12:00 12:00 4:00 8:00 =(checkout<checkin)+CheckOut-CheckIn4 12:00 0:00 12:00 6:00 6:00 Big_Formula_Above 5 18:00 9:00 15:00 1:00 14:00 6 23:00 12:00 13:00 4:00 9:00 If you want the HOURS, multiply by 24. C2: =(B2<A2)+B2-A2 D2: =IF(B2>=A2,MAX(0,MIN(B2,"18:00")-MAX(A2,"8:00")),MAX(0,"18:00"MAX(A2,"8:00"))+MAX(0,MIN(B2,"18:00")-"8:00")) E2: =(B2<A2)+B2-A2 - D2 grayed area for reference not used in calculation of columns D & E (B2<A2) is a logical express equates to either 1 (i.e. 24 hours), or 0 to be added/subtracted ------

Total core hours (9AM-5PM) between two datetimestamps, but only weekdays
On 8/8 8/9/1999 JM (jmklee) reply to Anthony R. Acosta. (accepted as is) I would like to calculate the difference in minutes between two dates, excluding the hours between 5pm to 8am and weekends. For example if the first date is 08/04/99 6:00pm and the end date is 08/05/99 9:00 am, I would like it to calculate as 60 minutes or one hour. You can use the NETWORKDAYS function from the Analysis Tool. A1 your first date and B1 your end date, both in full format mm/dd/yy hh:mm You can have A1 and B1 separated with as many days you want. The total time is in C1 (formatted with [h]:mm ) : You might want to use notepad to eliminate end of line characters from these formulas: A B Sat 1 12/01/2001Mon 12/03/2001 16:00 07:00 2 =A6+A4 =A8+A6 3 4 8:00 Length of core hours for one day 5 7:00start time (doesnt count until either 8AM or 9AM) on 1st day 6 16:00end time (one hour short on 9AM-5PM) on last day 7 12/01/2001start date 8 12/03/2001end date 9 10 07:00Original Formula with NETWORKDAYS 9:00 - 17:00 original 11 08:00Original Formula with NETWORKDAYS but 8:00-16:00 instead of 9:00-17:00 12 23:00Formula without NETWORKDAYS corrected to use 9AM to 5PM 13 24:00Formula without NETWORKDAYS corrected to use 8AM to 4PM (spaces in formula removed) 14 24:00Formula without NETWORKDAYS corrected to use 8AM to 4PM (spaces in formula removed) 15 Formulas used in A9:A12 note 8 hour interval, with specific time range =MIN("8:00",MAX("0:00","17:00"+INT(A1)A1))*NETWORKDAYS(A1,A1)+MIN("8:00",MAX(B1-"9:00"16 07:00 INT(B1)))*NETWORKDAYS(B1,B1)+"8:00"*(MAX(0,NETWORKDAYS(A1,B1)-2)(INT(INT(A1)/INT(B1)))) =MIN("8:00",MAX("0:00","16:00"+INT(A1)A1))*NETWORKDAYS(A1,A1)+MIN("8:00",MAX(B1-"8:00"17 08:00 INT(B1)))*NETWORKDAYS(B1,B1)+"8:00"*(MAX(0,NETWORKDAYS(A1,B1)-2)(INT(INT(A1)/INT(B1)))) =MIN("8:00",MAX("0:00","17:00"+INT(A1)-A1)) +MIN("8:00",MAX(B1-"9:00"-INT(B1))) 18 23:00 +"8:00"*(MAX(0, INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1))) =MIN("8:00",MAX("0:00","16:00"+INT(A1)-A1))+MIN("8:00",MAX(B1-""8:00""-INT(B1))) 19 24:00 +"8:00"*(MAX(0,INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1))) =MIN(A4,MAX("0:00","16:00"+INT(A1)-A1))+MIN(A4,MAX(B1-"8:00"-INT(B1))) 20 24:00 +A4*(MAX(0,INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1)))

Problems entering Date or Time when Transition options in effect (#date123)

Lotus 1-2-3 transition options interfere with entry of date and times, would suggest turning them off after all you are using Excel not 1-2-3. Under Tools --> Options --> Transition turn off everything that says transition, and hit the [OK] button The DateWatch utility (or a similar 3rd-party program) can cause problems with entering fractions, it appears under tools menu as Date Migration, and can be turned off through Tools/Addins menu. Rob Bovey 1999->01->15 <uVKu548X GA.205@cppssbbsa04>

Problems enter Fractions, but get Dates (#entryprob)

Entering stock prices as 1/2 or 1/64 and getting dates: Solution enter 0 1/2 or 0 1/64 instead. See Pasting fractional stock prices show up as dates in Excel for an attempt at fixing.

Countdown to a Date (#countdowny2k)


Countdown to the New Millennium (year 2001). Some additional Excel 2000 tips.
=DATEVALUE("1-January-2001")-TODAY()&" days remaining in 2000"

VBA -- Visual Basic for Applications (Programming Language) -- VBA

Date & Time Functions in VBA (#vbadate)


Refer to your VBA HELP file for more information. VBA Help is obtained where you can edit your code. In XL97 and up it is Alt+F11, then F1, and in XL95 invoke F1 (Help) when editing a module sheet. Date DateDiff Returns a Variant (Date) containing the current system date. DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]]) Dont confuse this with the DATEDIF Worksheet Function

DateSerial DateSerial(year, month, day) DateValue DateValue(date) -- MyDate = DateValue("February 12, 1969") Day Hour IsDate Minute Month Now Second Day(date) Hour(time) -- returns integer between 0 and 23 IsDate(expression) -- returns True or False Minute(time) -- returns 0 to 59 Month(date) Now -- Returns a Variant (Date) specifying the current date and time according your computers system date and time. Second(time) -- returns whole number between 0 and 59, inclusive

TimeSerial TimeSerial(hour, minute, second) TimeValue TimeValue(time) -- MyTime = TimeValue("4:35:17 PM") Weekday Weekday(date, [firstdayofweek])

Year

Year(date)

If you want absolute control over adding a number of months to another date where the day of the month of the first date does not exist in the date that is xx months later.
Function Addmonths(dateref As Date, _ add_months As Long, Optional nextmonth as boolean) As Date Addmonths = Application.Min(DateSerial(Year(dateref), _ Month(dateref) + add_months, Day(dateref)), _ DateSerial(Year(dateref), Month(dateref) + add_months + 1, nextmonth)) End Function

ISDATE (a builtin VBA function)

(#isdate)
Sub Ratman02() Cells.Interior.ColorIndex = 0 'reset all interior color Dim cell As Range For Each cell In Application.Intersect _ (Selection, ActiveSheet.UsedRange) If IsDate(cell) Then If cell.Value > Date Then cell.Interior.ColorIndex = 3 'Red - FUTURE DATE Else cell.Interior.ColorIndex = 8 'Cyan -- valid date End If Else: cell.Interior.ColorIndex = 14 'Teal -- NOT a Date End If Next cell End Sub

This example was tested on 08/05/2000 (Aug 5, 2000 US Format) A B C D 10 11 08/01/2000 12 09/01/2000 08/05/2000 13 08/05/2000 10/01/2000 14 08/05/2000 08/05/2000 15 08/05/2000 Hello 16 08/05/2000 08/05/2000 17

More information on Colors in Excel and the Excel color palette.

Converting Text Dates to Excel Dates (#MakeTrueDate)


If the Text dates and your Regional Dates are both US date format, for a manual conversion: - Copy an empty cell - Select Range for cells to be converted - Edit, Paste Special, Add - Format range as Date An alternative is to copy a 1f and use Paste Special with Multiply instead. Use of a macro simply needs to reassign the value and Excel will recognize it as a date. (only if your date formats are US)
Sub MakeTrueDate() 'Converts Text Dates(US) to dates(US), Tom Ogilvy, 2001-03-24 programming Dim rng As Range Set rng = Intersect(ActiveCell.EntireColumn, _ ActiveSheet.UsedRange) 'next assume first row is a header Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1) rng.NumberFormat = "mm/dd/yyyy" rng.Value = rng.Value

End Sub

Converting Text Entry Dates to Excel Dates with Text to Columns (#t2cols)
What to do when Text Entry Dates Do NOT Match your Regional Settings Converting Text entry dates to Excel dates is easily done by multiplying by 1, but when the date entries do not match your regional settings you can use Text to Columns to fix up your dates. Actually this would be more of a problem for those with UK/European/Australian dates than those with US dates. My dates are US and my Regional short date is mm/dd/yyyy which having US dates is assumed to be m/d/y. If you specify a month greater than twelve, Excel will assume you reversed the day and month -- there is such an example below. This question was raised by someone in Australia working with MetaStock which generates an Excel spreadsheet with US text dates instead of UK/Australian dates. C D E F Single column processed with 1 Original Specified format for F3:G8 Text to Columns 2 Text to Columns (source) MDY DMY MDY DMY 3 Format on row 4 @ m/d/yy m/d/yy ddmmmyyyy ddmmmyyyy 4 Date 4/5/99 04/05/1999 05/04/1999 05Apr1999 04May1999 5 Date 3/4/00 03/04/2000 04/03/2000 04Mar2000 03Apr2000 6 Date 9/10/99 09/10/1999 10/09/1999 10Sep1999 09Oct1999 7 Date 12/13/99 12/13/1999 12/13/1999 13Dec1999 13Dec1999 8 Date 13/12/01 13/12/01 12/13/200113/12/01 13Dec2001 9 Date 24/9/01 24/9/01 09/24/200124/9/01 24Sep2001 10 shows alignment ooo oooooooooooo ooooooooooooo ooooooooooooo ooooooooooooo ooooooooooooo A B

Adjusting Date Time Stamps from other systems (#adjust)


UNIX maintains date and time as seconds past Jan 1, 1970. Convert to Excel use with = DATE(1970, 1, 1) + (A1/24/60/60) More information J.E. McGimpsey, 2001-09-26and function.

Debugging Date Entries (#debug)


Regional settings and cell formatting can cause problems with dates if anything is incorrectly applied. This topic is to help you identify what you actually have. One thing you can do to quickly determine if entries are Text or Numbers is to use: Select ALL cells (Ctrl+A), Edit (Ctrl+G), [Special], GoTo, Number & Constants (only constants)

Dates are Numbers. The format for a number can be changed at any time to another number format. Data that was entered as text or with a text format must be reentered if the format is changed to a number format. By formatting the cell range, then reentering the value you can convert text entries containing numbers to number constants. The fastest way to reenter a single cell is to select cell, press F2, then Enter. You can convert a lot of text entries containing numbers to number constants by multiplying by 1 or by adding a blank (truly empty) cell. Select empty cell and copy (ctrl+c) then select the range, then edit, paste special, add. You can effect a similar change by selecting a cell with a value of 1, copy (ctrl+c), select the range to be affected, paste special, multiply. You can use one of the REENTER macros on my Reformat page (join.htm) to speed up the process, there are several variations there, including TrimALL which specifically converts CHAR(160) which is the HTML symbol &nbsp; (non breaking space) to a space then trims spaces from the left and right sides of the cell value.

A DATE 1 ENTRY 2 06/07/1999

Regional Dates in use are US: short: mm/dd/yyyy long: mmmm dd, yyyy -- Some entries (E16:E25) below have formats overridden in cell. B C D E F Display Formula

Entered as 6/7/99 with US Regional Settings 3 06/07/1999 5 =LEN(A3) 4 06/07/1999 36318 =TEXT(A4,"General") =TEXT(A5,"dd mmm 5 06/07/1999 07 Jun 1999 yyyy") =TEXT(A5,"mmm dd, 6 06/07/1999 Jun 07, 1999 yyyy") 7 06/07/1999 TRUE =ISNUMBER(A7) 8 06/07/1999 D4 =CELL("format",A8) 9 06/07/1999 v =CELL("type",A9) 10 06/07/1999 36318 =getformula(A10) 11 06/07/1999 m/d/yy =getformat(A11)

The Example to the left has entry as 6/7/99 and my Regional Settings are for the US, but my short date regional setting is modified to include the full 4 digit year so my Regional Setting Short Date format is mm/dd/yyyy -- interestingly the format shows as m/d/yy because that is the default US regional setting. Note cell B35 has code 0160 simulating an HTML symbol of &nbsp; (non breaking space). When trying to debug date entries note what you see 1) in the formula bar 2) in the cell 3) in the format (Format, cell) TEXT ENTRY 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 6/7/99 Display Formula

12 06/07/1999

56 =CODE(RIGHT(A12,1))

13 14 15 16 17 18 19 20 21 22 23 24 DATE Display Formula ENTRY 06/07/99 Entered as shown on Formula bar 07/06/1999 5 =LEN(A16) 07/06/1999 36318 =TEXT(A17,"General" =TEXT(A18,"dd mmm 07/06/1999 07 Jun 1999 yyyy") =TEXT(A18,"mmm dd, 07/06/1999 Jun 07, 1999 yyyy") 07/06/1999 TRUE =ISNUMBER(A20) 07/06/1999 D1 =CELL("format",A21) 07/06/1999 v =CELL("type",A22) 07/06/1999 36318 =getformula(A23) 07/06/1999 dd/mm/yyyy =getformat(A24)

Entered with quote on Formula bar 6 =LEN(E16) 36318 =TEXT(E17,"General" 07 Jun =TEXT(E18,"dd mmm 1999 yyyy") Jun 07, =TEXT(E18,"mmm dd, 1999 yyyy") FALSE =ISNUMBER(E20) G =CELL("format",E21) l =CELL("type",E22) 6/7/99 =getformula(E23) General =getformat(E24)

25 07/06/1999 56 =CODE(RIGHT(A25,1)) 26 has 27 Char(160) Display Formula so is text 28 06/07/99 has Char(160) 29 06/07/99 9 =LEN(A28) 30 06/07/99 06/07/99 =TEXT(A30,"General" =TEXT(A31,"dd mmm 31 06/07/99 06/07/99 yyyy") =TEXT(A31,"mmm dd, 32 06/07/99 06/07/99 yyyy") 33 06/07/99 D1 =CELL("format",A33) 34 06/07/99 l =CELL("type",A34) 35 06/07/99 FALSE =ISNUMBER(A35) 36 06/07/99 06/07/99 =getformula(A36) 37 06/07/99 dd/mm/yyyy =getformat(A37) 38 06/07/99 160 =CODE(RIGHT(A38,1))

6/7/99

57 =CODE(RIGHT(E25,1))

Column is Display Formula Text 6/7/99 Entered into Text field 6/7/99 6 =LEN(E28) 6/7/99 36318 =TEXT(E30,"General" 07 Jun =TEXT(E30,"dd mmm 6/7/99 1999 yyyy") Jun 07, =TEXT(E30,"mmm dd, 6/7/99 1999 yyyy") 6/7/99 G =CELL("format",E33) 6/7/99 l =CELL("type",E34) 6/7/99 FALSE =ISNUMBER(E35) 6/7/99 6/7/99 =getformula(E36) 6/7/99 @ =getformat(E35) 6/7/99 57 =CODE(RIGHT(E36,1))

Bus Schedule with PM times as boldface (#bus)


You cannot specify boldface in regular cell formatting. Conditional Formatting could do the boldface but that is all. A macro is needed to change the time and formatting so that that 1:00 and 13:00 both appear as 1:00 with the PM appearing in bold, and both without AM or PM. Example: Original Bus Schedule Sheet A B C D 3 8:00Point B 7:00Point F 4 12:00Point C 12:00Point E 5 13:00Point D 16:00Point D 6 17:00Point E 17:00Point C New Bus Schedule Sheet A B C D 3 8:00Point B 7:00Point F 4 12:00Point C 12:00Point E 5 1:00Point D 4:00Point D 6 5:00Point E 5:00Point C

A more complete example with code can be seen on Bus Schedule page

Coverage Chart (#coverage)


A 7 NAME 8 Arlene B C D E F G H I J K L M N O P Q R S T U

HRS 8 7.5 9 Betty 7.0 10 Cathy 7.5 X X 11 Coverage 1 1

9 XX X XX 2 3

10 X X X 3

X X X 3

11 12 X XX X X XX X X 3 2 2 2

13 14 15 X XX X X X XX X X XX 3 2 2 2 3

X X X 3

16 X X X 3

17 X X XX 3 1

B8: =COUNTA($C8:$U8)*0.5 C11: =COUNTA(C$8:OFFSET(C11,1,0)) Conditional formatting for the range C8:U10 CF1: =COUNTA(C8) CF2: =NOT(COUNTA(C8))

1904 Date System vs 1900 Date System (#1904)


The difference in days between the two systems is 1462, which you may encounter if you try to change the date system in a workbook, or if you copied a worksheet from another workbook. Tools, Options, Calculation, 1900/1904 Dates

Real-Time Clock in Excel (#clock)


Sometimes someone wants a real-time clock in their worksheet. Personally I think the System time in the corner of the screen serves this purpose, and there are shortcuts for entering System Date/Time into a Cell or within code. The solution here will produce screen blinking as the clock updates at one second intervals which may differ by up to one second from the system clock in your computer. For time from the National Institute of Standards and Technology (NITS), see Time Information topic for more information.
From: Harald Staff

12:35:17 AM X

xxxxx

Here is code for a clock that runs in worksheet one, cell A1, unless You type X in B1, then it stops. Modify location and criteria&rsquos for Your own use. Sub clock() If ThisWorkbook.Worksheets(1).Range("B1").Value = "X" Then Exit Sub ThisWorkbook.Worksheets(1).Range("A1").Value = Format(Now, "hh:mm:ss AM/PM") Application.OnTime Now + TimeSerial(0, 0, 1), "clock" End Sub Best wishes Harald (I got this code from this group some months ago, and I am sorry that I did not archive the creator for later credits. Thank You, whoever You are.) See revised Real-Time Clock (below).

Revised Real-Time Clock


Similar to the above. Harold supplied a revised version that recommends use of a start button and a stop button. Instead of simply replacing the coding I have included both so you can see the coding. I see the cursor move and blink momentarily every second on XL95. You can create buttons using the Tools Form bar. The buttons would not ordinarily coincide with cell

boundaries, but they could appear to as in the following example. Again repeating what was said before: Personally I think the System time in the corner of the screen serves this purpose, and there are shortcuts for entering System Date/Time into a Cell or within code. A clock on the worksheet will be stealing cycles whether you see the clock or not, even if the page isnt active, and you will probably notice a slow down with large workbooks. You can show seconds on the Task Bar Clock by using TClockEx without turning your expensive computer into a wall clock.

12:35:17 AM

Start Stop Clock Clock

Dim stopit As Boolean 'on top of module! Sub startclock() 'assign start button stopit = False clock End Sub Sub clock() If stopit = True Then Exit Sub ActiveWorkbook.Worksheets(1).cells(1, 1).Value = _ Format(Now, "hh:mm:ss") Application.OnTime (Now + TimeSerial(0, 0, 1)), "clock" End Sub Sub stopclock() 'assign stop button stopit = True End Sub

Note the Worksheets(1). This indicates the first worksheet in your workbook. You might want to change that to a specific sheet such as Worksheets("Clock Sheet") or Worksheets("Sheet7") so as to not wipe out any sheet that just happens to have become the first sheet. This also applies to the previous example.

Elapsed Time and Count-Down Timer (#timers)


See chrono.zip on Steve Bullens site. See this thread in Google Usenet Archives, specifically look for Stephen Bullens reply.

Stop Watch, Alarm, and Count Down Timers


Excel does not have a SLEEP function so you have to calculate the time at which you will resume. The following will issue three beeps, I give a little more time after the first beep. I still see timing done with a loop to waste machine cycles. On a mainframe that would be well over 30 years behind the times. Anyway I think the code I have below will work better across platforms and more to the point with processors with different speeds instead of a timing loop.
Sub Beeper()

Beep start2 = Now() + TimeSerial(0, 0, 0.9) Application.Wait start2 For i = 2 To 3 start2 = Now() + TimeSerial(0, 0, 0.8) Application.Wait start2 Beep Next i End Sub

Stopwatch to time inner processing in seconds. Timer is the number of seconds since midnight, so a correction has been included for negative number resulting from passing through midnight during execution. (Limited to duration of 24 hours, longer times possible by including date) -- also see More on Stop Watches below.
Sub Timing_Test() Dim timing As Double 'timing will be shown at end timing = Timer 'Floating point register used ' .... lots of processing here .... timing = Timer - timing if timing < 0 then timing = timing + 1440 'midnight correction MsgBox Format(timing, "0.000") & " seconds" End Sub

This example will sound an Alarm at a specified time.


Sub Alarm() Dim beepat As String beepat = InputBox("Give Alarm at", "hh:mm:ss " & _ Format(Now, "mm:hh"), "17:00") If beepat = "" Then MsgBox "cancelled" Exit Sub End If Application.OnTime TimeValue(beepat), "BeepMe" End Sub

Example of a Count Down Timer


Sub CountDownTimer() Dim beepat As String beepat = InputBox("Count down Timer hh:mm:ss i.e. 10:00", _ "Time now is " & Format(Now, "hh:mm:ss"), "3:00") If beepat = "" Then MsgBox "cancelled" Exit Sub End If Application.OnTime (Now + TimeValue(beepat)), "BeepMe" End Sub Sub beepme() Beep Application.OnTime (Now + TimeSerial(0, 0, 0.8)), "beepme2" End Sub Sub beepme2() Beep

Application.OnTime (Now + TimeSerial(0, 0, 0.8)), "beepme3" End Sub beepme3() Beep End Sub

More on Stop Watches -- Continued (#StopWatchcontd), Also take a look at my page on Slow Response Inevitably someone is going to try to use Excel to time runners to 100ths of a second. Without examining whether Excel is really feasible for this or not here are some newsgroup searches on how to do it. The best solutions will probably require winmm.dll for high resolution. All were found starting with: http://groups.google.com/advanced_group_search? q=group:*Excel*&num=100 search on all words: "stop watch" real group:*excel* threadm=3A782332.5D8EC99E%40consumer.org search on all words: stopwatch record group:*excel* selm=eldUXJUlCHA.2000%40tkmsftngp04 threadm=66sapo%2448e%241%40news-srv1.fmr.com

Dates formatted in a VBA macro subroutine (#vbaformat)


As text [a10].Value = Format(Now, "mm/dd/yyyy hh:mm:ss AM/PM") Range("A11").Value = Format(Now, "hh:mm:ss") activecell.offset(0,4).value = Format(Now, "hh:mm:ss") Assign datetime interval constant and format as date/time activecell.offset(0,4).format = "mm/dd/yyyy hh:mm:ss AM/PM" activecell.offset(0,4).value = Now

Dates Prior to 1900 and George Washingtons birthday (#gwash)


John Walkenbach has created as an addin to handle years 0100-9999 in his Extended Date Functions Add-In, which requires at least XL97. 0100-9999 is the date range supported by VBA, so dont know what calendar changes, if any, are actually supported. I dont know which calendars are in use in Johns XDATE functions but anything has to be better than what is builtin to Excel. I will mention the following excerpt from the 1990 World Almanac to highlight some difficulties of working with older dates.

The British Government imposed the Gregorian calendar on all its possessions, including the American colonies, in 1752. The British decreed that the day following Sept. 2, 1752, should be called Sep. 14, a loss of 11 days. All dates preceding were marked O.S., for Old Style. In addition New Years day was moved to Jan. 1 from Mar. 25. George Washingtons birth date, which was Feb. 11, 1731, O.S., became Feb. 22, 1732, N.S. What is now the US had three different dates for the Julian to Gregorian calendar shift alone - 1582 for the areas under Spanish and French control, 1752 for areas under British control, and 1863 for Alaska, when it was purchased from Russia. I think everyone would agree that that Excel is severely lacking in its ability to work with date calculations such as dates in 1800 especially since there are people living who were born in 1800s and in treating 1900 as a leap year as had one of its predecessors, Lotus 1-2-3. General Information on Date and Time (not necessarily related to Excel)

Time Information, for those who are serious or just interested (#timeinfo)
If you computer clock is consistently off by several minutes when you power up again, you probably have a bad battery (search: computer clock/CMOS batter*), and should check your OEM site for more information. Replacing a battery yourself should be a cheap solution.

Official US Time NIST -- National Institute of Standards and Technology, and USNO -- US Naval Observatory Time & Frequency Division, NIST (Boulder, Colorado) Time, Set Your Computer Clock Via the Internet, NIST Network Time Service (NTS) -- nistime-32bit.exe.lnk, http://www.boulder.nist.gov/timefreq/service/its.htm

See the Public Domain NIST Software area for downloadable synchronization software. Then if you want to set up with automatic synchronization, choose an NIST server near you then to have the time synchronize when you start up your machine add once within the Target box in the properties window of the shortcut in the \Windows\Start Menu\Programs\Startup folder: i.e. C:\Internet\Nisttime\nistime-32bit.exe once I tried automatic synchronization originally, but did not like it, probably useful if you have an always online connection through

a cable, but I prefer to see what the difference actually is, so I run the program myself each day. Program uses sampling to improve accuracy. If the time gets way out every day, you will probably have to replace a small battery in your computer. What Time Is It? (US Navy) Another Realtime Clock (US Navy) International Time zones MS KB Q262680, List of Simple Network Time Protocol Time Servers on the Internet Outside of the US http://www.arachnoid.com/abouttime/index.html excellent synchronization. GMT - Greenwich Mean Time, Universal World Time -http://greenwich2000.com/ Greenwich 2000 Home Page -- http://greenwich2000.com/ World Time -- http://www.worldtime.com/cgi-bin/wt.cgi World Time Server anywhere, anytime -http://www.worldtimeserver.com/ -- get the Atomic Clock synchronization, perhaps questionable lots of adverts. Some Date/Time Tables or Calculators Daylight Savings Time, Dates for Change, in the US. How to get local time based on the GMT or GPS time, GPS units typically report Universal Time (GMT time zone). Calculators: sunrise/sunset, Solar Position Calculator

Clocks including in the System Tray and related downloads (#clocks)


Alarm Clock, Turn your $3,000 computer into a $30 Alarm Clock. Karen Kenworthy, writer for former Windows Magazine, writing their Power Users column. [LG] Clock.exe is supplied with Windows NT, and shows time hh:mm:ss and the date (but not day of the week). Can be resized for a small display or even a full screen display. Black text or outlined text on gray background. Choice of local time or GMT, and can be displayed without title bar. TClockEx, Taskbar Clock Enhancer v1.4.2 , Dale Nurden. http://www.rcis.co.za/dale/tclockex/index.htm, to see seconds, date and more in tray clock, CPU% not displaying on Win2000. Mouse over shows 16KB RAM avail 87% memory load, Fri 02/11/2000 (42/365) CPU xx% your customized mini summary, mouse-click a calendar, right-click more options. Display of time and/or date of your choice and colors on taskbar. (originally seen in zdnet hotfree downloads) Title Bar Clock, v1.4 [62k] W9x/2k/XP FREE, {PC clock} TBC displays the day, month, time, and megabytes of free physical memory in the right side of the Title Bar of the main window

Something frequently asked in newsgroups is how to place a clock into an Excel spreadsheet, something you should not do as it will severly affect/curtail your Excel usage. (see #clock).

Date Information, for those who are serious or just interested (#dateinfo)
Information Please: Today in History, Events that happened on this date in history, world, US news, current events today calendar timeline. [chronology, almanacs, Homework Center]

Mostly Useless but Interesting Information (#interesting)


The Julian and Gregorian Calendars Quarters, how year is divided into quarters: English (seasonal), Scots(different seasonal), US (tax). What time is it? VCR Clock Time | geekBlue.net, You'll find a link basically to the most annoying image in the world.

Examples
Calendar Control in Excel, Using, Microsoft article. Date Calculation Worksheet Examples. Some additional date information can be found in used in footers. =GetFormula(cell) can be used to show formula in use as seen in the examples on this page. Working with dates, one frequently ends up with validly formatted dates appearing as text. Reentering each of the dates will change them from text to dates. F2 then Enter is faster, still better is to use a macro to accomplish this. See ReEnter() macro. Related Information ON/OFF site

Related Information (#related)


Related Information on Other Sites
My DATETIME page appears to have concentrated on formatting dates and times, while Chip Pearson appears to have concentrated more on calculations in his DATETIME pages. Nothing remains static on web pages so you may want to recheck pages from time to time. I also have a Date Calculation page which shows sample calculations in a simulated spreadsheet as a companion to this page.

DATETIME one of Chip Pearsons Excel Pages Chips site contains a series of how tos and macros for dates and times. Additional macros and how tos can be found in holidays. Another of Chips pages Date And Time Entry for XL97 describes how to enter time or dates without separators -- i.e. 1234 for time entry 12:34. Third Friday of the Month and additional Worksheet Functions For Dates And Times similar to 4th Monday of a month (above). Scheduling Procedures With OnTime Date and Time [Excel] at The Access Web -- Dev Ashish Time and Date, A guide to time zones, calendars (by Country), sunrise/sunset, dates on/off daylight savings time. World Clock and Configure your own cities for time checking. Since Excel will not accept dates before 1900, DATEDIF() will not work for dates before 1900. As previously mentioned John Walkenbach has created as an addin to handle years 0100-9999 in his Extended Date Functions Add-In, which requires at least XL97. http://www.j-walk.com/ss/excel/files/xdate.htm and also on Johns site is Spreadsheet History. Also see XL: Excel Incorrectly Assumes 1900 Is a Leap Year -- The actual treatment of dates in Johns XDATE functions is that of VBA, which is better than the treatment found in Excel. Also of interest A downloadable employee time sheet can be found in John Walkenbachs http://www.j-walk.com/ss/excel/files/index.htm Obtaining and Changing a Files Created, Accessed and Modified Dates at Randy Birchs VBnet (Visual Basic File API Routines) -- this page tells how to obtain/change a file's created, last access, and last modified dates. Identifies five different times (System Time, Filetime, local systemtime or filetime, MS-DOS, Windows). For instance Filetime is stored as 100-nanosecond intervals since Jan 1, 1601. (does not specifically relate to Excel). This example allows you to change the stored times. (functions: GetFileDateString, GetSystemDateString) Calendars, <B662658A.1A7%[email protected]> site is http://www.altcal.com/ also see Q213795 below. TimeCore Solo ~ time management for the Individual, v1.1 [4.0M] W9x/2k/XP FREE (not Excel), {Time management} TimeCore Solo is a time tracking program with a recording engine that captures time worked on a task or project. [LockerGnome]

Related newsgroup postings


Calendar control added for entry into active cell from a Calendar, Chip Pearson, 2002-02-24, misc.

Microsoft Knowledge Data Base (MS KB)


Useful search argument in Excel For Windows area: xl

date and xl and time and

KB72578 XL: Converting Hours in Decimal Form to HH:MM:SS Format

KB81026 XL: Calculating Days Remaining in a Time Period KB81694 XL: Formula to Calculate Number of Days in Month KB94870 XL: Changing the Date or Time Format in a Header or Footer KB99349 XL: Working with Time Periods That Exceed 24 Hours KB112361 XL: Negative Date/Time Value Displayed as Pound Signs (###) KB129277 XL: Undocumented Worksheet Function DATEDIF (see note earlier about removal from MS KB or see Chip Pearsons page for information pertaining to the missing KB129277 - datedif) KB151503 XL: How to Call a Macro Repeatedly on a Fixed Time Interval KB161607 XL97: Macro to Change the Date/Time Format in a Header/Footer KB164406 XL: How Microsoft Excel Works with Two-Digit Year Numbers. KB181370 XL: Microsoft Excel Incorrectly Assumes 1900 Is a Leap Year KB183626 XL: How the DateSerial Function Works with Year Arguments KB116281 XL: Visual Basic Procedures for Julian Date Calculations KB168435 XL: Maximum Times in Microsoft Excel, (10,000 in XL95 and later) KB213795 XL2000: How to Create a Monthly Calendar. Also see 2002 Excel Calendar (in Template Gallery) KB214330 XL: Description of the differences between the 1900 date system and the 1904 date system in Excel, This article describes the two date systems and the problems that you may encounter when you use workbooks that use different date systems KB214094 XL: HOW TO: Use Dates and Times in Excel 2000 KB214391 XL2000: How Microsoft Excel Works with Two-Digit Year Numbers KB287027 XL2002: Web Query Converts Numbers That Contain Hyphens into Dates. solution: Excel 2002 provides a long needed option to Disable date recognition when importing data. KB812385 - XL2002: Cells Automatically Format with Hijri Date Format When You Type a- Before a Number.

This page was introduced on June 19, 1998.

(last update: Tue, 23 Aug 2005 01:57:38 GMT)

[My Excel Pages -- home] [INDEX to my site and the off-site pages I reference] [Site Search -- Excel] [Go Back] [Return to TOP]
Please send your comments concerning this web page to: David McRitchie send email comments

Copyright 1997 - 2004, F. David McRitchie, All Rights Reserved

You might also like