简体   繁体   中英

Excel VBA Macro Help - Mandatory Cells

New user, was referred to your helpful website by a friendly team member.

Problem: Trying to force a user in excel to fill in a cell in a column (column O) before filling in a cell in columns IL. The problem lies in that not every cell in the columns needs to be filled in. I've found a VBA code that has somewhat helped but the problem is the pop up will still occur if column O is filled before there is text in just one of the cells in column IL (and therefore the error occurs unless all 4 cells in the row are filled in). As mentioned, the goal is (for example) to get O264 to be filled in first before any of the cells in column I,J,K or L264 are filled in.

Further exacerbating this issue is there are multiple rows I need this applied to, believe this is where the range fits in. However, playing with the range line in excel does not work in the way I've tried.

Code below:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("I:L")) Is Nothing Then
If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub
If Target.Offset(, -1).Value = "" Then
MsgBox "You must first enter feedback in column ""O"""
Target.Value = ""
Target.Offset(, -1).Select
End If
End If
End Sub

This could be a case where you might need to aid the user a little more. You could do that by hiding the dependent cells, by locking them, by greying them out, etc. My feeling is that displaying a message box whenever a user enters data in the wrong order is a little too reactive.

In the example below, the target cells are locked and greyed until something is entered in column 'O'. You'd also need to create a list of target rows if you have more than one.

In your code behind the appropriate sheet, the skeleton code below should get you started. I've included a couple of helper functions to make the code a little clearer for you:

Option Explicit

Private Const SHEET_PASSWORD As String = "xyz" 'whatever password you choose.
Private Const TARGET_ROWS As String = "2,4,6" 'your target rows, separated by commas.
Private Const TARGET_COLUMN As String = "O"
Private Const DEPENDENT_COLUMNS As String = "I:L"

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, cell As Range

    Set rng = Intersect(Target, Me.Columns(TARGET_COLUMN))
    'Exit routine if we're not in the target column.
    If rng Is Nothing Then Exit Sub

    'Process the target column cells.
    For Each cell In rng.Cells
        If IsTargetRow(cell.Row) Then
            SetDependentStates cell
        End If
    Next
End Sub

Private Sub SetDependentStates(cell As Range)
    Dim DependentRange As Range

    'Define the Dependent range based on passed cell row.
    Set DependentRange = Intersect( _
        cell.EntireRow, _
        Me.Range(DEPENDENT_COLUMNS) _
    )

    'Lock/unlock and paint Dependent rows, based on
    'contents of passed cell.
    Application.EnableEvents = False 'prevent capture of change event.
    Me.Unprotect SHEET_PASSWORD
    With DependentRange.Cells
        If Len(cell.Value) = 0 Then
            .ClearContents
            .Locked = True
            With .Interior
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .ThemeColor = xlThemeColorDark1
                .TintAndShade = -0.249977111117893
                .PatternTintAndShade = 0
            End With
        Else
            .Locked = False
            With .Interior
                .Pattern = xlNone
                .TintAndShade = 0
                .PatternTintAndShade = 0
            End With
        End If
    End With
    Me.Protect SHEET_PASSWORD
    Me.EnableSelection = xlUnlockedCells
    Application.EnableEvents = True
End Sub

Private Function IsTargetRow(rowNum As Long) As Boolean
    Dim v As Variant

    'Tests if the pass row number is in the target row list.
    For Each v In Split(TARGET_ROWS, ",")
        If CLng(v) = rowNum Then
            IsTargetRow = True
            Exit Function
        End If
    Next
End Function

Public Sub InitialiseDependentStates()
    Dim v As Variant
    Dim cell As Range

    'Define your unlocked cells.
    'This is a simple example, adjust as you wish.
    With Me
        .Unprotect SHEET_PASSWORD
        .Cells.Locked = False
        .Protect SHEET_PASSWORD
        .EnableSelection = xlUnlockedCells
    End With

    For Each v In Split(TARGET_ROWS, ",")
        Set cell = Me.Range(TARGET_COLUMN & v)
        SetDependentStates cell
    Next
End Sub

You'll likely want to initialise the dependent states when the workbook is opened. Do this in the code behind the Workbook:

Private Sub Workbook_Open()
    Sheet1.InitialiseDependentStates 'use whichever sheet you're using.
End Sub

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