简体   繁体   中英

Make an excel cell mandatory, based on value of other 2 cells

So.. I've an excel where 2 consecutive cells can be marked with the same value (mostly Text), based on this 2 cells the value of the 3rd cell should be filled mandatorily by the user.

The range of cells can be different as I need to use the same snippet cross many excels.

Any help would be sincerely appreciated.

Many thanks! :)

There's more then one way to skin a cat, but probably the easiest way to do it would be to include a vba sub which (on some trigger, like submitting) checks the value of cell 1 and 2 and IF that value is whatever you want to trigger on... if cell 3 is blank prompt the user to fill in box three.

IF Range("A1").Value == "Trigger" And Range("A2").Value == "Trigger" And Range("A3") == "" Then msgBox("You must fill in cell A3")

If you add a break statement like End Sub, the sheet can't continue until that cell is filled.

This is an example for A1 , B1 , C1 enter the following event macro in the worksheet code area:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim A As Range, B As Range, C As Range
    Set A = Range("A1")
    Set B = Range("B1")
    Set C = Range("C1")
    If A <> "" And B <> "" And C = "" Then
        Application.EnableEvents = False
            C.Select
        Application.EnableEvents = True
        MsgBox "please enter a value in cell C1"
    End If
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code - this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM