Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Dim rngChange As…
- User
Option Explicit
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 = "x" 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 End Sub
The code above changes resultOffset.Value to 'y' but the offset is one cell too far to the right
- Assistant
To fix the issue of the offset being one cell too far to the right, you need to adjust the offset value by subtracting 1. Here's the updated code:
Option Explicit
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 - 1 ' Calculate the offset and subtract 1 Dim resultOffset As Range Set resultOffset = resultCell.Offset(, offsetVal) If resultOffset.Value = "x" 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