Insert a Row using a Macro to maintain formulasThe macro InsertRowsAndFillFormulas() has been updated 2000-09-02 INSRTROW is a macro to copy the selected line making the requested number of copies of it downward, but to include only the formulas. Leaving the constants to be manually filled in. (button ) I wanted to be able to insert a row and maintain the formulas but not to copy data that would be unique for the line. The propagation of data would be misleading so I want it to be blank so I have to enter it myself. See also use of OFFSET in formulas which simplifies the insertion, and deletion of rows with the InsertRowsAndFillFormulas macro and allows you to sort the rows; whereas, sorting rows containing simple addition and subtraction of relative addresses would make a mess.
Want to insert a line so select row 2 or any cell on row 2 such as D2, then hit the macro button to invoke InsertRowsAndFillFormulas.
The formulas have been copied but cells that do not contain formulas are empty, and the data can now be entered with the results as follows:
Normally the dates in Column B are entered using the shortcut key for the current date [Ctrl+semi-colon]. My DR/CR are the opposite of what most checkbooks show, since I prefer to keep records for myself and not for my bank or their point of view. ¤ If you maintain a checkbook in Excel you can add up deposits for a deposit slip by selecting the range and looking at the SUM= on the status bar. Why must we use that funning looking OFFSET Worksheet FunctionIn order to use the InsertRowsAndFillFormulas macro, the formulas must be entered naming only the cellnames found on the current row. By referencing cells in the current row any insertion or deletion of lines will cause formulas to be updated. In order to refer to cells elsewhere but to name only cell addresses in the current row, OFFSET will be used as follows:
Replication is made easier by grabbing and dragging the fill handles and with the use of shortcuts Ctrl+D (Fill Down), and Ctrl+R (Fill Right). OFFSET makes Replication/Deletion of Rows tie in better with the other rows, and of course, makes possible the InsertRowsAndFillFormulas macro described in this page. A more explicit example of OFFSET and using the macro described below can be found in Using OFFSET to maintain formulas Code for the InsertRowsAndFillFormulas MacroTo obtain a macro that would do what I wanted I posted to the newsgroup what I wanted and failed at that. I then found and included a macro close to what I wanted and described again exactly what I really needed. This worked very well and the solution involved a one line addition that removed non formulas from the inserted line providing exactly what I wanted.The macro is installed on a module sheet in my personal.xls The code below has extra blank lines to help identify long lines it they get wrapped when you copy them. For more information on why INTERSECT and how SpecialCells are used in the following macro see comments with Proper_Case macro. Sub InsertRowsAndFillFormulas(Optional vRows As Long) ‘ Documented: http://www./dmcritchie/excel/insrtrow.htm ‘ Re: Insert Rows -- 1997/09/24 Mark Hill Addition insertion of rows, Examples:Sub InsertBeforeTotalinColumnA() Columns("A:A").Find(What:="total", After:=Range("A2"), LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=False).Offset(-1, 0).Activate Call InsertRowsAndFillFormulas(1) ‘see my insrtrow.htm page End Sub Sub Macro18() Dim C As Long C = 3 ‘Number of rows to insert Range("b15").Select ‘below this cell ActiveCell.Offset(1, 0).EntireRow. _ Resize(rowsize:=C).Insert Shift:=xlDown End Sub Install a button to invoke macro for InsertRowsAndFillFormulasI created a macro button that has colors and resembles a inserted line Refer to toolbars page for some help in setting up such a button.Background for INSRTROW macro (comment added 2000-02-01)Creating such a macro proved difficult and I could not get the answers I wanted for a generic solution from the newsgroup. http://groups.google.com/groups?oi=djq&ic=1&selm=an_327694444So I searched what is now Google archives for the closest solution (1997/09/24 Mark Hill) to my problem and then posted that code with a description of what I really wanted and was surprised that a one line addition (1998/03/11 Bill Manville) would remove the constants. Aren‘t newsgroups great! Also from Bill‘s reply learned to use OFFSET in formulas to remove the need to modify formulas after running the macro. A small price to pay for the benefit. http://groups.google.com/groups?oi=djq&ic=1&selm=an_333104660 When you think everything is done, find out that the macro will not work for grouped (multiple selected) sheets. Gary L. Brown, 2001-01-16, added looping through the selected sheets; and I sloppily corrected that to reselect the sheets in the group before macro was run. Some customized changes‘---- additionally clear out columns B and D in the inserted rows ‘---- Columns B & D were entered as formulas, but are to be cleared anyway Dim multi_range As Range Dim new_area As Range Set multi_range = Application.Union(Range("b:b"), Range("d:d")) Set new_area = Selection.Offset(1).Resize(vRows).EntireRow Intersect(new_area, multi_range).ClearContentsTo retain constants, code as formulas: i.e. ="abc" Worksheet_Change eventThe following Worksheet_Change event could be used to create the formulas on the line when the date is typed into the B column. The InsertRow macro is still preferable because the copy will copy the formatting for cells (number & colors). More on Change Events on my event.htm page.A change event will not recognize entry of a date with a short-cut (Ctrl+;), nor will it recognize a change by pasting a value. Option Explicit Private Sub Worksheet_Change(ByVal Target As Excel.Range) ‘to install -- rightclick on the sheettab of the corresponding ‘ sheet and choose ‘view code‘. Paste the following procedure ‘ in the module. If Target.Column <> 2 Then Exit Sub If Target.Row = 1 Then Exit Sub Dim R As Long R = Target.Row Target.Offset(0, -1).Formula = _ "=IF(B" & R & "="""","">"",WEEKDAY(B:b,1))" Target.Offset(0, 5).Formula = _ "=OFFSET(G" & R & ",-1,0)-F" & R & "+E" & R Target.Offset(0, 6).Formula = _ "=IF(NOW()>B" & R & "+5,""*"","""")" Target.Offset(0, 10).Formula = _ "=IF(OR(G" & R & "<250,M" & R & " <300),""XX"","""")" Target.Offset(0, 11).Formula = "" then _ Target.Offset(0, 11).Formula = _ "=IF(H" & R & "<>"""",OFFSET(M" & R & ",-1,0)+E" _ & R & "-F" & R & ",OFFSET(M" & R & ",-1,0))" ‘=IF(H604<>"",OFFSET(M604,-1,0)+E604-F604,OFFSET(M604,-1,0)) Target.Offset(0, 12) = R End Sub Extended Formats and FormulasRelated to automatically entering formulas, this may be useful for some applications. I found the option very annoying.It would not be practical for examples on this page as when I find out what the actual posting date is, I substitute that into the cell in place of formula generated space or asterisk. Also a column I add so that I could sort on if I mixed things up gets automatically extended.
Actually I now have it turned on, it probably is just a matter of getting used to it. You might take a look at Q231002 -- XL2000: How Auto Extend List Behavior Works Some Macros for inserting blank rows on alternate linesThe following macro will insert a row BEFORE any row in which the cell in Column A is not blank, with the exception of before the first row. It inserts lines from the bottom of the Used range upward so inserted lines do not interfere with counting. Blank here is anything that looks like a blank. If you want to insert regardless of content in Column A, then remove the condition.Sub InsertALTrows() ‘David McRitchie, misc 2000-01-27 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual ‘pre XL97 xlManual Dim i as long For i = Cells.SpecialCells(xlLastCell).Row To 2 Step -1 If Len(Trim(Cells(i, 1))) <> 0 Then Rows(i).Insert ‘ 1 is Column A Next i Application.Calculation = xlCalculationAutomatic ‘pre XL97 xlAutomatic Application.ScreenUpdating = True End SubInsert1or2RowsBeforeNonBlankA() use the following code to insert 1 or 2 rows before the any value in Column A. If there is a value in A immediately above only one row; otherwise, 2 rows. For i = Cells.SpecialCells(xlLastCell).Row To 2 Step -1 If Len(Trim(Cells(i, 1))) <> 0 Then If Len(Trim(Cells(i - 1, 1))) <> 0 Then Rows(i).Insert Shift:=xlDown Else Rows(i + 1).Resize(2).Insert Shift:=xlDown End If End If If there is a value in A immediately above; oth othnav The following macro will insert a row between existing rows in a selection any row Sub InsertALTrowsInSelection() ‘David McRitchie, misc 2001-06-30 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual ‘pre XL97 xlManual Dim i As Integer For i = Selection(Selection.Count).Row To Selection(1).Row + 1 Step -1 Rows(i).Insert Next i Application.Calculation = xlCalculationAutomatic ‘pre XL97 xlAutomatic Application.ScreenUpdating = True End SubAn alternative to this may simply be to increase the height of all rows to provide some spacing that would not be lost due to sorting. Another alternative might be the use of Conditional formatting to color alternate rows: Insert Blank Rows on Column A change of valueSub InsertRow_A_Chg() Dim irow As Long, vcurrent As String, i As Long ‘// find last used cell in Column A irow = Cells(Rows.Count, "A").End(xlUp).Row ‘// get value of that cell in Column A (column 1) vcurrent = Cells(irow, 1).Value ‘// rows are inserted by looping from bottom For i = irow To 2 Step -1 If Cells(i, 1).Value <> vcurrent Then vcurrent = Cells(i, 1).Value Rows(i + 1).Insert End If Next i End Sub Related codingIs there a way to calculate a cell reference? i.e. +C2 calculated as +C(1+1)=INDIRECT(C2) =INDIRECT("C"&1+1) =INDIRECT(address(row(C1)+1, column(C1))The inclusion of address helps correct formulas if you insert or delete lines. Adjusting coding when named cells are usedIf the formula to be replicated starts in A2, try the following:=OFFSET(pension,row(a2)-row($A$2),0)+OFFSET(taxable_income,row(A2)-row($A$2),0) Bank Reconciliation by Check NumbersThought you might find this one interesting. VLOOKUP was suggested by Myrna Larson in the MISC newsgroup.Problem: Reconcile bank statement. Two files received electronically. One includes checks issued with check number in Column A, and the other file has checks paid and also includes the check #. How can the two columns of check numbers be compared to show outstanding checks. Solution: Try a VLOOKUP formula with the last argument set to 0. If a check isn‘t found in the bank‘s list, the formula will show #NA. I like my checkbook worksheet, but if you don‘t here is a program that keeps track of type transaction as well Easy Checkbook for Excel PC World. Inserting Lines -- Manual AlternativeFor more on shortcuts see my shortcut pages shortx2k, and shortx95 for additional information.
Manually removing constants
Provide numeric constant in a formula i.e. =3.14 Provide text constant in a formula i.e. =text("abc def","@") Use some text boxes to provide information. Deleting RowsThe antithesis of InsertRowsAndFillFormulas described here is DeleteBlankRows in Chip Pearson‘s Excel pages. Caution: I had to comment out two lines beginning with Application.Calculation to avoid a runtime error 1005 on my system (XL95 under WinNT). Also check out an article by John Walkenbach Delete All Empty Rows in a Flash (Oct 1997 PC World). If you delete rows at end of spreadsheet you should also review my article Reset Last Cell Used.If you are going to delete rows you will want to work your way up from the bottom, so you don‘t trip yourself up by skipping rows you haven‘t examined or by deleting the wrong row. dim rw as long For rw = ActiveSheet.UsedRange.Rows.Count to 1 step -1 if cells(rw,"A")="" then rows(rw).delete nextThe above loop is really not needed, read more about this in delempty.htm (Dana DeLouis) On Error Resume Next ‘ In case there are no blanks Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete ActiveSheet.UsedRange ‘Resets UsedRange for Excel 97Delete All Rows that are completely empty Sub RemoveEmptyRows() Application.ScreenUpdating = False ‘xlManual below in Xl95 Application.Calculation = xlCalculationManual Dim rw As Long, iCol As Long For rw = ActiveSheet.UsedRange.Rows.Count To 1 Step -1 If Application.CountA(Rows(rw).EntireRow) = 0 Then _ Rows(rw).Delete Next Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True ‘xlAutomatic above in xl95 End SubWithin your own existing code possibilities include: Selection.Rows.EntireRow.Delete ActiveCell.Rows.EntireRow.Delete Cells(16, 2).Rows.EntireRow.Delete Selection.EntireRow.Delete More on Inserting RowsRows("15:15").Insert Shift:=xlDown ‘insert cells based on content in A1‘ N = Range("A1").Value ActiveCell.Resize(N).EntireRow.Insert Adding/Subtracting with sign on RightTransactions came in from my new bank with a single entry column (col C), and a Balance column (Col D). The following is placed in Column E to verify the figures supplied in column D to make sure all transactions are present. Actually I used Replace ALL to remove + from Balance column and $ from Transaction and Balance Column.=IF(RIGHT(C5,1)="-",E4-LEFT(C5,LEN(C5)-1), Fix Right Minus signFix Right Minus -- A Worksheet solutionThis is a continuation of the previous topic and example. Following is a Worksheet solution to display a single value from another cell.=IF(RIGHT(D12,1)="-",-1*LEFT(D12,LEN(D12)-1)+0,D12) FixRightMinus -- A Macro solutionChange right minus text constant cells in selection to negative numbers. You can change formatting before or after running the macro.Sub FixRightMinus() ‘David McRitchie 2000-02-04 rev 2000-05-01 ‘ rev. based on Dana DeLouis and Peter Surcouf ‘ prior to XL97 use xlManual and xlAutomatic Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim cell As Range On Error Resume Next For Each cell In Selection.Cells.SpecialCells(xlConstants, xlTextValues) cell.Value = CDbl(cell.Value) Next cell Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End SubSolution above was revised based on solution which uses CDbl and On Error Resume from (Peter Surcouf and Dana DeLouis), which converts entire sheet rather than selected range. In any case the following is redundant and is replaced by one line.If Right(cell.Value, 1) = "-" Then cell.Value = -1 * Left(cell, Len(cell.Value) - 1) End IfXL2002 has a button [Advanced], on wizard panel to indicate trailing minus (when you tell it what format General|Date|skip|etc). Dave Peterson 2002-01-02 programming Clear certain columns on active rowSince INSRTROW the focus of this page clears out constants, I thought this macro might be of interest. It will indiscriminently delete particular columns on the row of the active cell and will not change the active cell.Sub ClearCells() ‘leo.heuser@get2net.dk, misc, 2000-11-22 Maintaining a Total at two Rows below last input data in Column AUse this formula in your last row i.e. last row is 20. (posted 2001-05-01 D.McRitchie) Inserting Two Blank RowsThe following is from Dana DeLouis, 2001-05-13, programming, where he points out that Resize is faster. Dana frequently comes up with time saving tips. If you look at the posting he also includes a programmed approach that does not involve a loop.Sub InsertTwoRows_v2() ‘Dana De Louis, programming, 2001-05-13 Dim r As Long For r = Range("A" & Rows.Count).End(xlUp).Row To 2 Step -1 Rows(r).Resize(2).Insert Next End Sub Printing Multiple Labels based on Column ASee macro RepeatRowsOnColumnA in Mail Merge for a macro to repeat rows based on number in Column A, which would be needed by Mail Merge to print multiple labels with same content. Related
|
|