Excel Vba Examples
Excel Vba Examples
Excel Vba Examples
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)
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
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
& 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)
(#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
(#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
(#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
(#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
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 ( ) 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 ( ) 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 (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() 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 ( ) 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.
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 ( ) 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
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)
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)
(#VAL)
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
(#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.
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
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
(#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
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
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 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.
(#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
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.
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
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
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
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)
(#aftlast)
End If Next i AFTLAST = cell ' or aftlast="" depending on what you want Application.Calculation = xlCalculationAutomatic 'in XL97 End Function
(#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
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
(#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
(#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 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)
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)**
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.
[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
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.
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
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 ( ) 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.
'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
B 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
B 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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
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
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.
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 ( ) or CHR(160) will be treated as a space which is CHR(32). The TrimALL macro is a another macro that takes the 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
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 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
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
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 -- 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.
End Sub
(#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.
(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
[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
'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
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
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
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]
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.
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]
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)
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.
(#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.
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.
Entered as:
Displays As
Actual value
3/31
31-Mar
d-mmm
36,616.00 03/31/2000
Mar-32 mmm-yy 03/31/2000 m/d/yy 03/31/2000 m/d/yy Mar-00 mmm-yy 3 General General
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)
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
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15
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
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.
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);_(* "-"??_);_(@_)
1 2 3 4 5 6 7 8
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.
3 Bobby 11/02/1985
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).
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)
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.
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).
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.
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.
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
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.
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
1 Format--> General General [h]:mm 2 Employee Start 3 Jan H. 4 Pat T. 8:20 10:55 2:35
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
8 9 10 11 12 13
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
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
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
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
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)))
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>
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.
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)
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
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
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 (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 (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))
A more complete example with code can be seen on Bus Schedule page
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))
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).
12:35:17 AM
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.
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
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
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
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]
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
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]
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.
[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
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.
(#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.
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.
Entered as:
Displays As
Actual value
3/31
31-Mar
d-mmm
36,616.00 03/31/2000
Mar-32 mmm-yy 03/31/2000 m/d/yy 03/31/2000 m/d/yy Mar-00 mmm-yy 3 General General
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)
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
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15
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
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.
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);_(* "-"??_);_(@_)
1 2 3 4 5 6 7 8
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.
3 Bobby 11/02/1985
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).
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)
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.
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).
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.
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.
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
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.
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
1 Format--> General General [h]:mm 2 Employee Start 3 Jan H. 4 Pat T. 8:20 10:55 2:35
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
8 9 10 11 12 13
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
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
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
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
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)))
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>
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.
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)
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
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
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 (non breaking space) to a space then trims spaces from the left and right sides of the cell value.
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 (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))
A more complete example with code can be seen on Bus Schedule page
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))
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).
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
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.
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
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
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
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]
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
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]
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.
[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