Sometimes when I run this code, it places the values in the correct cell. Othertimes it…
- User
Sometimes when I run this code, it places the values in the correct cell. Othertimes it places the values in the wrong position. Does it have something to do with the variable stored in memory?
Private activeCellRange As Range
Private Sub UserForm_Initialize() ' Assign the active cell to the property variable Set activeCellRange = activeCell End Sub
Private Sub StartEndButton1_Click() ' Update the start and end times in columns AD and AE using the stored active cell activeCellRange.Offset(0, 28).Value = StartTime.Value activeCellRange.Offset(0, 29).Value = EndTime.Value ' Hide the form Me.Hide End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) ' Cancel the close event to avoid closing the form unintentionally If CloseMode = 0 Then Cancel = True Me.Hide End If End Sub
- Assistant
The issue you are experiencing may be related to the way your code is assigning the active cell to the
activeCellRangevariable.In your
UserForm_Initializeevent, you are assigning the active cell using theactiveCellproperty. However, this property may refer to a different cell each time the code runs, depending on which cell is selected in the worksheet.To ensure that you are always selecting the correct cell, you can modify your code to use the
Targetparameter of theWorksheet_SelectionChangeevent. This event is triggered whenever the user selects a different cell in the worksheet.