gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
Private Sub Worksheet_Change(ByVal Target As Range) Dim rngChange As Range Dim rngValues…
- User
Private Sub Worksheet_Change(ByVal Target As Range) Dim rngChange As Range Dim rngValues As Range Dim rngOffset As Range
Set rngChange = Intersect(Target, Me.Range("AC3:AG18")) If rngChange Is Nothing Then Exit Sub Application.EnableEvents = False Set rngValues = Me.Range("AB3:AB18") Set rngOffset = rngValues.Offset(, -1) ' Offset by 1 column to the left (AB -> AA) Dim cell As Range For Each cell In rngChange If cell.Value = "y" Then Dim rowNum As Long rowNum = cell.Row - rngChange.Rows(1).Row + 1 ' Calculate the relative row number Dim lookupValue As Variant lookupValue = rngValues.Cells(rowNum, 1).Value ' Get the corresponding value from AB3:AB18 Dim resultRng As Range Set resultRng = Union(Me.Range("D3:D18"), Me.Range("L3:L18"), Me.Range("T3:T18")) Dim resultCell As Range Set resultCell = resultRng.Find(lookupValue, LookIn:=xlValues) If Not resultCell Is Nothing Then Dim offsetVal As Long offsetVal = rngChange.Columns(1).Column - rngOffset.Columns(1).Column ' Calculate the offset Dim resultOffset As Range Set resultOffset = resultCell.Offset(, offsetVal) resultOffset.Value = "y" End If End If Next cell Application.EnableEvents = TrueEnd Sub
The following code works perfectly. However I would like to add the following conditions.
resultOffset.Value can only be changed to "y" if the current value is 'Z' If the current value is not 'Z' then pop up message box "Current Bay is not Free on this day" and exit sub
- Assistant
Here is the updated code with the conditions you mentioned:
Private Sub Worksheet_Change(ByVal Target As Range) Dim rngChange As Range Dim rngValues As Range Dim rngOffset As Range
Set rngChange = Intersect(Target, Me.Range("AC3:AG18")) If rngChange Is Nothing Then Exit Sub Application.EnableEvents = False Set rngValues = Me.Range("AB3:AB18") Set rngOffset = rngValues.Offset(, -1) ' Offset by 1 column to the left (AB -> AA) Dim cell As Range For Each cell In rngChange If cell.Value = "y" Then Dim rowNum As Long rowNum = cell.Row - rngChange.Rows(1).Row + 1 ' Calculate the relative row number Dim lookupValue As Variant lookupValue = rngValues.Cells(rowNum, 1).Value ' Get the corresponding value from AB3:AB18 Dim resultRng As Range Set resultRng = Union(Me.Range("D3:D18"), Me.Range("L3:L18"), Me.Range("T3:T18")) Dim resultCell As Range Set resultCell = resultRng.Find(lookupValue, LookIn:=xlValues) If Not resultCell Is Nothing Then Dim offsetVal As Long offsetVal = rngChange.Columns(1).Column - rngOffset.Columns(1).Column ' Calculate the offset Dim resultOffset As Range Set resultOffset = resultCell.Offset(, offsetVal) If resultOffset.Value = "Z" Then resultOffset.Value = "y" Else MsgBox "Current Bay is not Free on this day" Exit Sub End If End If End If Next cell Application.EnableEvents = True