Pop up a message in vba - 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.

Related

Update a cell value with Row and Column number for use in indirect function based on which cell is selected

Hi I have a spreadsheet similar to below
Where when I click on a cell (red cell), I want to return the row and column number to another cell for use in an indirect lookup (blue cell)
Ideally I want to only update the cell value if it's within a set range or at least limit it only to that worksheet for error handling.
Hope that's clear... not an easy thing to google. My experiments with
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
MsgBox ActiveCell.Row
End Sub
Have returned nothing, not even a message box even though macros run fine. Any ideas?
Based on your example. Make sure your code is in the appropriate sheet module, not a standard module and make sure Application.EnableEvents=True (your existing code should have done something).
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
If Intersect(Target(1), Range("C4:H9")) Is Nothing Then Exit Sub
Range("J3").Value = Cells(Target(1).Row, 2) & "," & Cells(3, Target(1).Column)
End Sub
Use this in the worksheet's private code sheet.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target.Cells(1), Range("C4:H9")) Is Nothing Then
Range("C4:H9").Interior.Pattern = xlNone
Cells(3, "J") = Join(Array(Cells(Target.Cells(1).Row, "B"), _
Cells(3, Target.Cells(1).Column)), Chr(44))
Target.Cells(1).Interior.ColorIndex = 3
End If
End Sub

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

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

VBA to format cells based on another cell not working

SOLVED: FOUND MY OWN WORKSHEET ERROR
The problem I was having was trying to use two worksheet_change events in the same workbook. Because I thought that was possible, I was just renaming the worksheet event in question when I received an error, thinking nothing of it. Both my original code and the answer provided work, when combined with my other worksheet_change event.
Thanks everyone.
Original Request:
I am trying to run a macro that does this:
every time cell r6 changes, run a macro that looks to see if the value in cell s9 is > or < 1, then format cells s9:t100 based on that.
I have the macro on its own to do the second part:
sub macro1()
If Range("S9").Value < 1 Then
Range("S9:S100,T9:T100").Select
Selection.NumberFormat = "0.0%"
Else
Range("S9:S100,T9:T100").Select
Selection.NumberFormat = "#,##0"
End If
end sub
This macro run on its own, works exactly as I want and formats the cells.
Then I have the worksheet event to call up that macro:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$R$6" Then
Call Macro1
End If
End Sub
When it is run to call up the same macro, it does not format the cells. They just stay as a % regardless of when cell r6 changes.
Any ideas why the worksheet event causes the macro to not work?
Try passing the worksheet object to your macro. This fully qualifies the Ranges to make sure you're working on the right area.
Also, you don't need to Select at all. Just use the range and directly change the settings.
Public Sub Macro1(ws as Worksheet)
If ws.Range("S9").Value < 1 Then
ws.Range("S9:S100,T9:T100").NumberFormat = "0.0%"
Else
ws.Range("S9:S100,T9:T100").NumberFormat = "#,##0"
End If
end sub
Sub test()
Macro1 ActiveSheet
End Sub
And in your Worksheet_Change...
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$R$6" Then
Macro1 Target.Worksheet
End If
End Sub

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

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