How to delete all row which contains "Grand Total" in Excel automatically? - vba

In my active sheet called Report I have 2 column I & F.
It has repeating cells containing text "Grand Total".
I would like to delete whole row if it contains Grand Total automatically.
VBA code would be nice.

With the following VBA code, you can quickly delete the rows with certain cell value, please do as the following steps:
Select the range that you want to delete the specific row.
Click Developer>Visual Basic, a new Microsoft Visual Basic for applications window will be displayed, click Insert > Module, and input the following code into the Module:
VBA code to Remove entire rows based on cell value(i.e. Grand Total):
Sub Delete_Rows()
Dim rng As Range, cell As Range, del As Range
Set rng = Intersect(Range("A1:D22"), ActiveSheet.UsedRange)
For Each cell In rng
If (cell.Value) = "Grand Total" _
Then
If del Is Nothing Then
Set del = cell
Else: Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.Delete
End Sub
Then click "Play/Run" button to run the code, and the rows which have certain value have been removed.
(Note: If you can't see Developer Tab in Excel Do these Steps: 1)Click the Office Button, and then click Excel Options. 2)In the Popular category, under Top options for working with Excel, select the Show Developer tab in the Ribbon check box, and then click OK.)

Using AutoFilter is very efficient. This can also be done without VBA (ie manually)
Main Sub
Sub Main()
Dim ws As Worksheet
Dim rng1 As Range
Dim StrIn As String
Dim rng2 As Range
Set ws = Sheets("Sheet1")
Application.ScreenUpdating = False
Set rng1 = ws.Range("F:F,I:I")
StrIn = "Grand Total"
For Each rng2 In rng1.Columns
Call FilterCull(rng2, StrIn)
Next
Application.ScreenUpdating = True
End Sub
Delete Sub
Sub FilterCull(ByVal rng2, ByVal StrIn)
With rng2
.Parent.AutoFilterMode = False
.AutoFilter Field:=1, Criteria1:=StrIn
.EntireRow.Delete
.Parent.AutoFilterMode = False
End With
End Sub

This should help get you started.
http://msdn.microsoft.com/en-us/library/office/ee814737%28v=office.14%29.aspx#odc_Office14_ta_GettingStartedWithVBAInExcel2010_VBAProgramming101
Also see similar question:
Delete a row in Excel VBA

Related

Excel VBA: Trigger macro on cut/paste/delete/insert events

I have a conditional formatting rule defined as macro, which deletes the old rules and replaces them with updates ones:
Sub setCondFormat()
Set Table = ActiveSheet.ListObjects("Rules")
Table.Range.FormatConditions.Delete
Set Attribute = Table.ListColumns("Attribute")
With Attribute.DataBodyRange.FormatConditions _
.Add(xlExpression, xlEqual, "=ISEMPTY(A2)")
With .Interior
.ColorIndex = 0
End With
End With
End Sub
The conditional formatting in Excel needs to be updated. Otherwise the
cell ranges in the rules get fragmented.
Let's say you have two rules:
Make $A$1:$A$30 red
Make $B$1:$B$30 blue Now select A10:B10 and copy/paste that to A20:B20.
What Excel will do is to delete the conditional formatting.
For A20:B20 from the rules that applied to those cells and add new
rules that have the formatting for A20:B20. You end up with four
rules:
Make =$A$20 red
Make =$B$20 blue
Make =$A$1:$A$19,$A$21:$A$30 red
Make =$B$1:$B$19,$B$21:$B$30 blue
This happens, when the table structure gets changed through cut/paste/delete/insert events.
How to trigger the above VBA macro on cut/paste/delete/insert events?
You could use a shortcut for your macro
VBA event trigger on copy?
If you don't want to go this way you'll need to use the Windows API:
Is there any event that fires when keys are pressed when editing a cell?
The solution I found is create a new Sheet with the content of your table when you open the Workbook. First you need to create a Module with the Public Variables.
Public OldRange As Range
Public NewRange As Range
Public Table As ListObject
Then, use the event Open of your Workbook.
Private Sub Workbook_Open()
Dim sh As Worksheet
Dim address As String
For Each sh In Worksheets
If sh.Name = "DATA" Then
Worksheets("DATA").Activate
ActiveSheet.Delete
End If
Next
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = "DATA"
Set sh = ActiveWorkbook.Sheets("Plan1")
sh.Activate
Set Table = ActiveSheet.ListObjects("Rules")
Set OldRange = Table.Range
address = Table.Range.address
Table.Range.Copy
Set sh = ActiveWorkbook.Sheets("DATA")
sh.Activate
Range(address).PasteSpecial (xlPasteAll)
End Sub
And then, use the event Worksheet_Change to verify the content of your original table with the earlier saved table.
Private Sub Worksheet_Change(ByVal Target As Range)
Set Table = ActiveSheet.ListObjects("Rules")
If Intersect(Target, Table.Range) Is Nothing Then Exit Sub 'this will guarantee that the change made in your sheet is in your desired table
Set NewRange = Table.Range
Dim rng As Range
Dim rngaddr As String
Dim TableChanged As Boolean
TableChanged = False
For Each rng In NewRange
rngaddr = rng.address
If rng.Value <> ActiveWorkbook.Sheets("DATA").Range(rngaddr).Value Then
'do something
TableChanged = True
End If
Next
End Sub
Remember: you need to save the content of your table every time you changed it.

How to run macro if based on other cells which automatically changes by formula

As per subject, what I need is to run macro based on other cells.
Here is the case :
cells G3 until the end of row contains data used formula =IF(B3="";"";(SUMIF('Incoming Goods'!$F$3:$F$1048576;'Current Stock'!B3;'Incoming Goods'!$M$3:$M$1048576)-(SUMIF('Outgoing Goods'!$D$4:$D$1048576;'Current Stock'!B3;'Outgoing Goods'!$J$4:$J$1048576))))--> i need to convert this formula to VBA
cells H3 should contain : If G3.value = 0 then "Out of Stock", else " "
And this sheet must be calculate every time data in G3 change automatically or any additional data on this sheet.
Already tried this code :
Private Sub Worksheet_Calculate()
Dim Current As Worksheet
Dim Rng1 As Range
Dim Target As Range
Set Current = Worksheets("Current Stock")
Set Rng1 = Current.Range("G:G")
Set Target = Range("H:H")
For Each Rng1 In Target
If Rng1.Value2 = "0" Then
Target.Value2 = "Out Of Stock"
Else
Exit Sub
End If
Next
End Sub
However, above code is Not working. Already try using Private Sub Selection Change() and Private Sub Selection Change() but still not working.
Any suggestion?
Thanks in advance
the answer to the first part is below:
ActiveCell.FormulaR1C1 = _
"=IF(R[2]C[1]="""","""",(SUMIF('Incoming Goods'!R3C6:R1048576C6,'Current Stock'!R[2]C[1],'Incoming Goods'!R3C13:R1048576C13)-(SUMIF('Outgoing Goods'!R4C4:R1048576C4,'Current Stock'!R[2]C[1],'Outgoing Goods'!R4C10:R1048576C10))))"
handy tip: to convert any excel formula to code, hit the record macro button, then click on the cell, press F2 key, then press enter, and stop recording macro. The code will now be in its own module in the vba editor.
This should do what you want.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
If Not Application.Intersect(Range("A1"), Target) Is Nothing Then
If IsNumeric(Target.Value) And Target.Value > 200 Then
Call YourMacroName
End If
End If
End Sub

Excel VBA - Capitalizing all selected cells in a column with formulas

I used the code from Siddharth Rout on the following thread to capitalize selected columns but ran into a Error '13' MISMATCH when I used it on a column with cells that had formulas in some of the range.
Excel VBA - Capitalizing all selected cells in column on double click
Here is the code that worked on non-formula based column data from the above link:
Sub ChangeToUpper()
Dim rng As Range
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
End If
Set rng = Selection
rng = WorksheetFunction.Transpose(Split(UCase(Join( _
WorksheetFunction.Transpose(rng), vbBack)), vbBack))
End Sub
I searched the forums and didn't find specifics related to this. So I googled it and Mr.Excel had this code but still gave the Error '13', when I cleared out of the error message everything was capitalized. Is there a way to eliminate getting this error?
Here is the code from Mr.Excel:
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
If Len(cell) > 0 Then cell = UCase(cell)
Next cell
Application.ScreenUpdating = True
End Sub
Check If Cell has formula and or errors, If yes then ignore.
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
'/ Exclude errors
If Not IsError(cell) Then
If Len(cell) > 0 And Not cell.HasFormula Then
cell = UCase(cell)
End If
End If
Next cell
Application.ScreenUpdating = True
End Sub

Application.Input box to enter range for copy and paste options

I have been trying to copy and paste from one sheet to another, whereby the cells should be copied with the pastelink feature, while making use of the input box to let the user enter the range where he wants to paste the copied data. The code works within the same sheet but not on a different one. Even if it works, it does not recognise the range I have entered in the input box. Instead, it recognises the cursor and pastes whereby the cursor is in the destination worksheet.
This is the code I used for the copying and pasting from sheet 1 to sheet 2. Is there any problem with the codes for which why it does not recognise the range I have entered in the input box?
Sub tryuserinput()
Dim rng As Range
Dim inp As Range
Selection.Interior.ColorIndex = 37
Set inp = Selection
Set rng = Application.InputBox("Copy to", Type:=8)
inp.Copy
rng.Select
Worksheets("Sheet2").Paste Link:=True
End Sub
Is this what you are trying?
Sub Sample()
Dim rng As Range, inp As Range
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
Else
Set inp = Selection
inp.Interior.ColorIndex = 37
End If
Set rng = Application.InputBox("Copy to", Type:=8)
If Not rng Is Nothing Then
rng.Parent.Activate
rng.Select
inp.Copy
ActiveSheet.Paste Link:=True
End If
End Sub
Revised because...I didn't research. Just use this line of code after you choose the range in other sheet.
inp.Copy Destination:=ThisWorkbook.Sheets("Sheet2").Range(rng.Address)

Get the column of a user selected cell using vba excel

Refer to this question: Let the user click on the cells as their input for an Excel InputBox using VBA.
I use this line of code Set rng = Application.InputBox(Prompt:="Select the cell you want to edit.", Title:="CELL TO EDIT", Type:=8) to ask the user to select a cell. If the cell that is selected is in column G then I will need to call a subroutine. So, I need to figure out what column the selected cell is in.
Thanks for the help!
Use rng.Column property to return column number:
Sub test()
Dim rng As Range
On Error Resume Next
Set rng = Application.InputBox(Prompt:="Select the cell you want to edit.", title:="CELL TO EDIT", Type:=8)
On Error GoTo 0
If rng Is Nothing Then Exit Sub
'column G=7
If rng.Column = 7 Then
'do something
End If
End Sub
If user can select more than one cell, change
If rng.Column = 7 Then
to
If Not Application.Intersect(rng, Sheets("Sheet1").Range("G:G")) Is Nothing Then