How to use VBA to execute a macro based on an IF statement? - vba

I want to run an Excel VBA code (all it will do is delete specific cells within the same row and I've turned on relative reference so that I can apply the Excel VBA code to all rows, if there's the appropriate "X") based on whether there is an X in a certain cell.
Here's what I've tried so far (the Excel VBA code is just called "Biology"):
If Range("C22").Value = "X" Then
Call macro_Biology
End If
I should add that I'm writing this under VBA section "GetATPLabel". Like I said, total noob, but I think I'm close, so any help is appreciated.

It sounds as if it is important that the Biology (or macro_Biology) macro needs to know which row it is supposed to work on. You can pass this information across to it with a parameter. Example:
Sub start_with_this()
Dim rw As Long, lr As Long
With ActiveSheet
lr = .Cells(Rows.Count, "C").End(xlUp).Row
For rw = 2 To lr
If UCase(.Cells(rw, "C").Value) = "X" Then
Call macro_Biology(rw)
End If
Next rw
End With
End Sub
Sub macro_Biology(r As Long)
' r is the row that was passed in.
' do something with r
End Sub
After initially starting the start_with_this macro, it goes through each cell in column C from row 2 to the last row with anything in it. If it finds an X or an x (case-sensitivity is removed by forcing the cell value to upper case before comparing) then it calls the second macro, macro_Biology and tells it what row to deal with.

Lets assume that Biology() is a sub in a standard module:
Sub Biology()
MsgBox "study biology!"
End Sub
To call this as you want, run:
Sub TestIt()
If Range("C22").Value = "X" Then
Call Biology
End If
End Sub
To call Biology() automatically if the user types an X in cell C22, Insert the following event macro in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Set intrs = Intersect(Target, Range("C22"))
If Not intrs Is Nothing Then
If intrs.Value = "X" Then
Application.EnableEvents = False
Call Biology
Application.EnableEvents = True
End If
End If
End Sub
To call Biology() automatically if a formula gives an X in cell C22, Insert the following event macro in the worksheet code area:
Private Sub Worksheet_Calculate()
If Range("C22").Value = "X" Then
Application.EnableEvents = False
Call Biology
Application.EnableEvents = True
End If
End Sub

Related

Unable to Activate Macro when Active Cell Changes Through formula

My aim is to trigger the advanced filter macro when cell B2 changes (a part of the filtering criteria). B2 is linked to another cell(in another worksheet) which dynamically gets data from external sources. The problem I am facing is that the macro does not activate automatically. Only when I manually change something in B2 is the macro activated. Otherwise the old criteria remains in place. A1 to G1 has the 7 categories and A2-G2 has the inputs for the filter. Only B2 changes effectively. I have not coded in VBA before so most of this code is copied from websites and modified for my workbook. Below is my code. Appreciate any help on this.
Option Explicit
'Create variable to hold values
Dim Monitored()
Sub Advanced_Filtering()
Range("A7:G730").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Range("A1:G2"), CopyToRange:=Sheets("Sheet3").Range("L1:R1")
End Sub
Private Sub Worksheet_Activate()
Monitored = Range("B2:C2").Value 'Read in value prior to any changes
End Sub
Private Sub Worksheet_Calculate()
Dim Xrg As Range, c As Range, x As Integer
Set Xrg = Range("B2:C2")
If Not Intersect(Xrg, Range("B2:C2")) Is Nothing Then
Application.EnableEvents = False
'Compare monitored cell with initial value
x = 1
For Each c In Range("B2:C2")
If c.Value <> Monitored(x, 1) Then
Call Advanced_Filtering
Monitored(x, 1) = c.Value
End If
x = x + 1
Next c
'Reset events
Application.EnableEvents = True
End If
End Sub
Probably the easiest fix would be to place the Worksheet_Change event under the cells that generate the value on your cell B2, as changes in formula values don't trigger the Change event... or you can change it to Worksheet_Calculate event instead, this will pick up changes in formula results as below:
Option Explicit
'Create variable to hold values
Dim Monitored
Sub Advanced_Filtering()
Range("A7:G730").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Range("A1:G2"), CopyToRange:=Sheets("Sheet3").Range("L1:R1")
End Sub
Private Sub Worksheet_Activate()
Monitored = Range("B2").Value 'Read in value prior to any changes
End Sub
Private Sub Worksheet_Calculate()
Dim Xrg As Range
Set Xrg = Range("B2")
If Not Intersect(Xrg, Range("B2")) Is Nothing Then
Application.EnableEvents = False
'Compare monitored cell with initial value
If Range("B2").Value <> Monitored Then
'Do things as a result of a change
Call Advanced_Filtering
'Reset Variable with new monitored value
Monitored = Range("B2").Value
End If
'Reset events
Application.EnableEvents = True
End If
End Sub
UPDATE:
To use a Range of cells instead of a single one, you should change the following:
Option Explicit
'Create variable to hold values
Dim Monitored()
Sub Advanced_Filtering()
Range("A7:G730").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Range("A1:G2"), CopyToRange:=Sheets("Sheet3").Range("L1:R1")
End Sub
Private Sub Worksheet_Activate()
Monitored = Range("B2:C2").Value 'Read in value prior to any changes
End Sub
Private Sub Worksheet_Calculate()
Dim Xrg As Range, c As Range, x As Integer
Set Xrg = Range("B2:C2")
If Not Intersect(Xrg, Range("B2:C2")) Is Nothing Then
Application.EnableEvents = False
'Compare monitored cell with initial value
x = 1
For Each c In Range("B2:C2")
If c.Value <> Monitored(1, x) Then
Call Advanced_Filtering
Monitored(1, x) = c.Value
End If
x = x + 1
Next c
'Reset events
Application.EnableEvents = True
End If
End Sub

Excel | autostart macro on cell value change | cause crash

first of all I'm not a VBA programmer but typically an end-user who uses snippets of code that I gather in forums like this in his spreadsheets, trying to understand what the code does. Code for which I thank you all!
My objective:
I have a spreadsheet that is basically an input-form for users.
Based on their input and selections via dropdown my intention is to guide them through the form by hiding & unhiding rows with input fields, presenting the users with the relevant questions.
On each row I have created an IF-formula that creates a 1 or 0 based on previous provided input
1 -> unhide the row , 0 -> hide the row.
So I'm looking for a macro that runs with every sheet calculation and hides or unhides the next rows as needed.
These formulas are in range I3:I70 on top of that I created a summary field in I2 =sum(I3:I70) so i thought I can either check changes in the range I3:I70 or changes on cell I2 to trigger the macro. [Neither solution fixed my problem]
I've tried several code examples discribed on the forums and I've tested the macros that checks for change in the range or the cell individually.
As long as I call a test macro with a MsgBox it works fine.
Also the macro that hides or unhides runs fine when I call it manually.
My problem:
When I let the 'auto'-macro call the 'hide'-macro, Excel simply crashes; no warnings, nothing --> just crash.
My code:
Private Sub Worksheet_Calculate()
Dim Xrg As Range
Set Xrg = Range("H3:H70")
If Not Intersect(Xrg, Range("H3:H70")) Is Nothing Then
Macro1
End If
End Sub
Sub Sample()
MsgBox "Yes"
End Sub
Sub Macro1()
Dim cell As Range
For Each cell In Range("H3:H70")
If Not IsEmpty(cell) Then
If cell.Value = 0 Then
cell.EntireRow.Hidden = True
End If
If cell.Value = 1 Then
cell.EntireRow.Hidden = False
End If
End If
Next
End Sub
Thanks for any suggestions and tips in advance.
JeWe
Never give up searching :-) I gave it a last search and found some code on the microsfof dot com site that seems to work.
Don't ask me the details but this seems to do what i'm looking for
Private Sub Worksheet_Calculate()
Dim LastRow As Long, c As Range
Application.EnableEvents = False
On Error Resume Next
For Each c In Range("H3:H70")
If c.Value = 0 Then
c.EntireRow.Hidden = True
ElseIf c.Value = 1 Then
c.EntireRow.Hidden = False
End If
Next
On Error GoTo 0
Application.EnableEvents = True
End Sub
It's late on my end of the world, going to sleep. Will update tomorrow.
Txs JeWe

VBA: How to automatically trigger macro without a button

I have made a macro that auto fill the formula on sheet1 whenever the row number of sheet2 is changed.
Is it possible to trigger it automatically without a button when i have any update on sheet2?
Sub Autofill()
Dim sg As Sheets
Dim Row As Long
Dim fillRow As Integer
Application.EnableEvents = False
Row = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
fillRow = Row - 1
Sheets("Sheet1").Select
Range("A1:E1").Select
Selection.Autofill Destination:=Range("A1:E" & fillRow), Type:=xlFillDefault
Application.EnableEvents = True
End Sub
You could try to create a sub like following:
Paste the following code. And change:
1) "D4" with your cells you want to "monitor"
2) Paste your macro in the line "Do things"
The problem is, your code is run everytime the focus is changed to another cell.
But you could also use Worksheet_BeforeDoubleclick if this is enough. Then every time you clicke twice the code will run
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
If Not Intersect(Target, Range("D4")) Is Nothing Then
'Do things
End If
End If
End Sub
Right-click on the sheet tab at the bottom of the scree, click 'view
code' then insert this following code in there.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Row As Long
Dim fillRow As Integer
This next line will exit the code if column A is not what is being
changed on the sheet. Delete it if you want the code to be triggered
by any change on any cell of the sheet.
if InRange(Target,Worksheets("Sheet2").range("A:A") = false then exit sub
Row = Worksheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
fillRow = Row - 1
Sheets("Sheet1").Select
Range("A1:E1").Select
Selection.Autofill Destination:=Range("A1:E" & fillRow), Type:=xlFillDefault
End Sub
Function InRange(Range1 As Range, Range2 As Range) As Boolean
InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function
use a Worksheet.SelectionChange-Event.
in the Worksheet-VBA for sheet2 add:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call Autofill()
End Sub
(This will be triggered if cell is changed, even if user does not leave the row, so check parameter Target.)

Macro with show messsage box if cell contains value

I would like to do a macro. My testing cells are on another sheet. Sheet - (data) Macro check a range ("D2:D10") if the cells contain value 12 if yes show me a message box "Go to add to system" and this cell where macro found a value will be set to 0.
I have this code but it doesn't work for me I don't known why. Can you help me?
Private Sub check(ByVal Target As Range)
For Each c In Worksheet("data").Range("D2:D10")
If Range("D2:D10") = 12 Then
MsgBox "Go to add to system"
Range ("D2:D10").value = 0
End If
Next c
End Sub
The code below will correct your code (it will run without errors):
Option Explicit
Private Sub check(ByVal Target As Range)
Dim c As Range
For Each c In Worksheets("data").Range("D2:D10")
If c.Value = 12 Then
MsgBox "Go to add to system"
c.Value = 0
End If
Next c
End Sub
However, you could go with a slightly different approach - by accomplishing what you are trying to achieve in the Worksheet_Change event (of "data" sheet).
Code
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range
' Optional : use if criteria below to check the range only
' if one of the cells inside range("D2:D10") has changed
If Not Intersect(Range("D2:D10"), Target) Is Nothing Then
' if you decide to use the "If"above, then you don't need the "For" loop below
For Each c In Range("D2:D10")
If c.Value = 12 Then
MsgBox "Go to add to system"
c.Value = 0
End If
Next c
End If
End Sub

Pop up a message in vba

I am working on a file which in one sheet lets call it summary, I have formula that calculate the values which Ienter manually in other sheets, so I want to have an vba code to notify me by pop up message that the calculation result in summary sheet is <=0 when doing data entry in other sheets.
I have found below code which works fine with only one cell but if I want to extend it to other cells in the same row results in error. Suppose I want to extend it to B9:CZ9.
Private Sub Worksheet_Calculate()
If Me.Range("B9").Value <= 0 Then _
MsgBox "Leave is finished!"
End Sub
Possible background:
Private Sub Worksheet_Calculate()
With Me.Range("B9:CZ9")
If Application.CountIf(.Cells, "<=0") = .Cells.Count Then _
MsgBox "Leave is finished!"
End With
End Sub
Private Sub Worksheet_Calculate()
Dim RNG As Range
Set RNG = Selection
For Each c In RNG
If c.Value <= 0 Then
MsgBox "Leave is finished!"
End If
Next c
End Sub
If I understood you correctly, maybe this code helps you (you have to put this code to the source of the correct worksheet you want to work this code on):
Private Sub Worksheet_Calculate()
Dim leave As Boolean: leave = False
For Each c In Me.Range("B9:CZ9").Cells
If c.Value <= 0 Then: leave = True
Next
If leave Then: MsgBox "Leave is finished!"
End Sub
This code works when something is calculated in a cell, for example when you type =0 into any of them, and don't give you lots of messageboxes.
If you want this to work when anything changes, use Private Sub Worksheet_Change(ByVal Target As Range)
Remember that extension xlsx cannot contain VBA codes. Therefore after implementing the code to the worksheet you want this code works on, you have to save it as macro-enabled workbook.