The code below works, but it is having some issues with the offset positioning. I have…
- User
The code below works, but it is having some issues with the offset positioning. I have hidden columns in sheet 'OTForm'. Can you provide an alternative to Offset in the copy event.
Sub CopyMatchingValues() Dim OvertimeSheet As Worksheet Dim OTFormSheet As Worksheet Dim OvertimeRange As Range Dim OTFormRange As Range Dim OvertimeCell As Range Dim OTFormCell As Range Dim LastRow As Long Dim i As Long Set OvertimeSheet = ThisWorkbook.Sheets("Overtime") On Error Resume Next Set OvertimeRange = Application.InputBox("Select range in column C", Type:=8) On Error GoTo 0 If OvertimeRange Is Nothing Or Not OvertimeRange.Columns(1).Column = 3 Then MsgBox "No valid range selected in column C.", vbCritical Exit Sub End If Set OTFormSheet = ThisWorkbook.Sheets("OTForm") Set OTFormRange = OTFormSheet.Range("B4") LastRow = 11 For Each OvertimeCell In OvertimeRange If OvertimeCell.Value = OTFormRange.Value Then OTFormSheet.Cells(LastRow, "A").Value = OvertimeCell.Offset(0, -2).Value OTFormSheet.Cells(LastRow, "B").Value = OvertimeCell.Offset(0, 1).Value OTFormSheet.Cells(LastRow, "C").Value = OvertimeCell.Offset(0, 16).Value OTFormSheet.Cells(LastRow, "D").Value = OvertimeCell.Offset(0, 17).Value LastRow = LastRow + 1 End If Next OvertimeCell End Sub
- Assistant
To avoid using the
Offsetfunction, you can use theCellsfunction with row and column numbers to access the desired cell. Here's the modified code:Sub CopyMatchingValues() Dim OvertimeSheet As Worksheet Dim OTFormSheet As Worksheet Dim OvertimeRange As Range Dim OTFormRange As Range Dim OvertimeCell As Range Dim OTFormCell As Range Dim LastRow As Long Dim i As Long Set OvertimeSheet = ThisWorkbook.Sheets("Overtime") On Error Resume Next Set OvertimeRange = Application.InputBox("Select range in column C", Type:=8) On Error GoTo 0 If OvertimeRange Is Nothing Or Not OvertimeRange.Columns(1).Column = 3 Then MsgBox "No valid range selected in column C.", vbCritical Exit Sub End If Set OTFormSheet = ThisWorkbook.Sheets("OTForm") Set OTFormRange = OTFormSheet.Range("B4") LastRow = 11 For Each OvertimeCell In OvertimeRange If OvertimeCell.Value = OTFormRange.Value Then OTFormSheet.Cells(LastRow, "A").Value = OTFormSheet.Cells(OvertimeCell.Row, OvertimeCell.Column - 2).Value OTFormSheet.Cells(LastRow, "B").Value = OTFormSheet.Cells(OvertimeCell.Row, OvertimeCell.Column + 1).Value OTFormSheet.Cells(LastRow, "C").Value = OTFormSheet.Cells(OvertimeCell.Row, OvertimeCell.Column + 16).Value OTFormSheet.Cells(LastRow, "D").Value = OTFormSheet.Cells(OvertimeCell.Row, OvertimeCell.Column + 17).Value LastRow = LastRow + 1 End If Next OvertimeCell End Sub