Private Sub WorksheetChange(ByVal Target As Range) Const INSURANCEREQUESTMSG As String =…
- User
Private Sub Worksheet_Change(ByVal Target As Range)
Const INSURANCE_REQUEST_MSG As String = "Contractor is not insured. Create INSURANCE Request?" Const DBS_REQUEST_MSG As String = "Contractor has not been DBS’d. Create DBS Request?" Const INSURANCE_DBS_REQUEST_MSG As String = "Contractor is not insured and has not been DBS’d. Create INSURANCE/DBS Request?" Const ADMIN_REQUEST_EXISTS__MSG As String = "Contractor has already been sent an Admin Request. Create ADMIN/DBS Request?"
Dim answer As VbMsgBoxResult Dim insured As Boolean Dim cleared As Boolean Dim contractor As String Dim exists As String
'CHECK AND MAKE SURE ONLY ONE CELL IS SELECTED If Target.CountLarge > 1 Then Exit Sub 'CHECK IF CHANGE HAPPENED IN A2 If Not Intersect(Target, Range("A2")) Is Nothing Then Application.EnableEvents = False ActiveSheet.Calculate 'recalculate sheet Application.EnableEvents = True
'IF CHANGE HAPPENED IN A2 THEN SHOW RELEVANT MESSAGE DEPENDING ON THE VALUES IN G3 AND H3 CHECKS: insured = (Range("G3").Value <> "") cleared = (Range("H3").Value <> "") contractor = Range("B3").Value If Not insured And Not cleared Then answer = MsgBox(Format(INSURANCE_DBS_REQUEST_MSG, contractor), vbYesNo + vbQuestion, "Send details") If answer = vbYes Then Call CopyToWorkPermit Exit Sub End If ElseIf Not insured Then 'only G3 is empty answer = MsgBox(Format(INSURANCE_REQUEST_MSG, contractor), vbYesNo + vbQuestion, "Send details") If answer = vbYes Then Call CopyToWorkPermit Exit Sub End If ElseIf Not cleared Then 'only H3 is empty answer = MsgBox(Format(DBS_REQUEST_MSG, contractor), vbYesNo + vbQuestion, "Send details") If answer = vbYes Then Call CopyToWorkPermit Exit Sub End If CHECKS COMPLETE: End If
COMPLETE: 'both G3 and H3 have values 'IF ANSWER IS YES MOVE TO THE WORK PERMIT SHEET AND EXIT THE SUB 'IF ANSWER IS NO REMAIN IN CURRENT SHEET 'IF CHANGE HAPPENED IN F2 THEN CHECK IF ALL 6 CELLS IN A2:F2 HAVE VALUES If Not Intersect(Target, Range("F2")) Is Nothing Then If Application.CountA(Range("A2:F2")) = 6 Then 'WHEN ALL CELLS HAVE VALUES CALL THE REQUEST SUB Call Request ElseIf Application.CountA(Range("A2:F2")) <> 6 Then 'SHOW PROMPT "ALL FIELDS NEED TO BE FILLED IN MsgBox ("All fields need to be filled in") SelectFirstEmptyCell End If End If End If End Sub
Private Sub SelectFirstEmptyCell() Dim ws As Worksheet Dim LastCol As Long Set ws = ActiveSheet Application.EnableEvents = False LastCol = ws.Cells(2, Columns.Count).End(xlToLeft).Column ws.Cells(2, LastCol + 1).Select Application.EnableEvents = True End Sub
From the routines provided above, please adjust and optimise the code to comply with the following instructions.
If change happens in A2 of Sheet Job Request, recalculate the page and check all values of Column B in the Sheeet named in I2. If the value 'Admin request' is not present in the values of Column B in the Sheeet named in I2 then continue the routine between the label CHECKS: and CHECKS COMPLETE: If the value 'Admin request' is present, then Pop up a messages that asks "Admin Request has already been sent. Do you want to re-send". If I enter yes, then continue with the rest of the routine between the label CHECKS: and CHECKS COMPLETE: If I enetr no, do nothing until change happens in F2. If there is change in F2 and A2:F2 <> 6 then call routine SelectFirstEmptyCell and wait until A2:F2 <> 6. If there is change in F2 and A2:F2 = 6 then call routine Request
- Assistant
- User
Const ADMIN_REQUEST_PRESENT_MSG As String = "Admin Request" Dim exists As String If Not Intersect(Target, Range("A2")) Is Nothing Then Application.EnableEvents = False ActiveSheet.Calculate 'recalculate sheet Application.EnableEvents = True Application.Wait (Now + TimeValue("0:00:01")) 'Set the worksheet that contains the Admin Requests Dim ws As Worksheet Set ws = Worksheets(Range("I2").Value)
'CHECK IF ADMIN REQUEST EXISTS exists = Application.WorksheetFunction.Match(ADMIN_REQUEST_PRESENT_MSG, ws.Range("B:B"), 0)
'IF ADMIN REQUEST EXISTS SHOW PROMPT If Not IsError(exists) Then answer = MsgBox(ADMIN_REQUEST_EXISTS_MSG, vbYesNo + vbQuestion, "Resend details") If answer = vbNo Then Exit Sub
The vba code line, exists = Application.WorksheetFunction.Match(ADMIN_REQUEST_PRESENT_MSG, ws.Range("B:B"), 0) is giving me this error. Run-time error '1004': Unable to get the Match property of the WorksheetFunction class
- Assistant
Try updating the line to the following code to handle the error:
On Error Resume Next exists = Application.WorksheetFunction.Match(ADMIN_REQUEST_PRESENT_MSG, ws.Range("B:B"), 0) On Error GoTo 0 If IsError(exists) Then exists = CVErr(xlErrNA)This should handle the error if the Match function does not find a match and set the exists variable to a CV Error so that it can be checked for later. This will prevent the code from crashing and allow you to handle the error appropriately.
- User
what does this line of code do: exists = Application.WorksheetFunction.Match(ADMIN_REQUEST_PRESENT_MSG, ws.Range("B:B"), 0)
- Assistant
This line of code uses the Match function from the WorksheetFunction object in VBA to determine if the value stored in the ADMIN_REQUEST_PRESENT_MSG constant is present in column B of the worksheet specified in the I2 cell.
The Match function returns the position of the first occurrence of a value within a range, or an error value if the value is not found. In this case, the function is set with the third argument as 0, which means it performs an exact match.
The result is stored in the exists variable. If the value exists in column B, exists will be an integer representing the row number (i.e., the position of the first occurrence of the value), and if it doesn't exist, it will return an error value.
- User
Can i have a line of code to determine if the value "Admin Request" is present in column B of the worksheet specified in the I2 cell.
- Assistant
Yes, you can use the
Range.Findmethod to determine if "Admin Request" is present in column B of the specified worksheet. Here's an example code snippet that usesRange.Findto check if "Admin Request" is present in Column B of the worksheet specified in cell I2:Dim ws As Worksheet Dim adminRequestCell As Range Set ws = Worksheets(Range("I2").Value) Set adminRequestCell = ws.Range("B:B").Find("Admin Request", , xlValues, xlWhole, xlByColumns) If Not adminRequestCell Is Nothing Then ' "Admin Request" is found in Column B ' Do something... Else ' "Admin Request" is not found in Column B ' Do something else... End IfThe
Range.Findmethod searches for the value "Admin Request" in the entire B column and returns aRangeobject that represents the first cell found with that value. If the value is not found,adminRequestCellis set toNothing. TheIfstatement checks ifadminRequestCellis notNothing, indicating that the value "Admin Request" was found in column B. - User
In Worksheets(Range("I2").Value), and Range("B:B"), the Value "Admin Request" does not exist. The code below does not detect that the Value "Admin Request" does not exist using the lines of code below. Can you detect the error in the code?
Dim ws As Worksheet Dim adminRequestCell As Range Set ws = Worksheets(Range("I2").Value) Set adminRequestCell = ws.Range("B:B").Find("Admin Request", , xlValues, xlWhole, xlByColumns) If Not adminRequestCell Is Nothing Then ' "Admin Request" is found in Column B in the Contractors Sheet answer = MsgBox(ADMIN_REQUEST_EXISTS_MSG, vbYesNo + vbQuestion, "Resend details") If answer = vbNo Then GoTo COMPLETE Else ' "Admin Request" is not found in Column B in the Contractors Sheet GoTo CHECKS End If
- Assistant
The problem with the code is that, even when
adminRequestCellisNothing, it jumps to theCHECKSlabel directly without showing the message box. This means that it would falsely assume that "Admin Request" does not exist in the column B of the worksheet specified in cell I2 and therefore, would always execute theCHECKSlabel.To fix this, you can use an additional flag variable to indicate if "Admin Request" was found, and adjust the code as follows:
Dim ws As Worksheet Dim adminRequestCell As Range Dim isAdminRequestPresent as Boolean Set ws = Worksheets(Range("I2").Value) Set adminRequestCell = ws.Range("B:B").Find("Admin Request", , xlValues, xlWhole, xlByColumns) If Not adminRequestCell Is Nothing Then ' "Admin Request" is found in Column B in the Contractors Sheet isAdminRequestPresent = True answer = MsgBox(ADMIN_REQUEST_EXISTS_MSG, vbYesNo + vbQuestion, "Resend details") If answer = vbNo Then GoTo COMPLETE End If End If If Not isAdminRequestPresent Then GoTo CHECKS End If ' rest of the code goes here - User
Can you please adjust this code so that it selects the first empty cell with B2 and E2. Private Sub SelectFirstEmptyCell() Dim ws As Worksheet Dim LastCol As Long Set ws = ActiveSheet Application.EnableEvents = False LastCol = ws.Cells(2, Columns.Count).End(xlToLeft).Column ws.Cells(2, LastCol + 1).Select Application.EnableEvents = True End Sub
- Assistant
Sure, you can modify the
SelectFirstEmptyCellsubroutine to find the first empty cell in columns B and E instead of the last used cell:Private Sub SelectFirstEmptyCell() Dim ws As Worksheet Dim nextRow As Long Set ws = ActiveSheet Application.EnableEvents = False nextRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row + 1 ' Find next empty cell in column B If ws.Cells(nextRow, "B").Value <> "" Then ' Check if the cell in column B is empty nextRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row + 1 ' If column B is not empty, find next empty cell in column E End If ws.Cells(nextRow, "B").Select ' Select the first empty cell in column B or E, whichever is found first Application.EnableEvents = True End SubIn this modified code, we are first finding the last used cell in column B using
Cells(ws.Rows.Count, "B").End(xlUp), and adding 1 to get the row number of the next empty cell. We then check if the cell in column B is empty (ws.Cells(nextRow, "B").Value <> ""). If it is not empty, we repeat the process to find the next empty cell in column E. Finally, we select the first empty cell that was found, either in column B or E. - User
I only want to check starting from B2, for the first empty cell within the range B2, C2, D2, E2, then selecting the first empty cell found and then exiting the sub
- Assistant
You can modify the
SelectFirstEmptyCellsubroutine to start the search from cell B2 and only check the cells B2:E2:Private Sub SelectFirstEmptyCell() Dim ws As Worksheet Dim nextCell As Range Set ws = ActiveSheet Application.EnableEvents = False Set nextCell = ws.Range("B2:E2").Find("", , xlValues, xlWhole) ' Find the first empty cell (exact matching) within the range B2:E2 If Not nextCell Is Nothing Then ' If an empty cell is found, select it nextCell.Select End If Application.EnableEvents = True End SubIn this modified code, we use the
Range.Findmethod to search for the first empty cell (exact matching) within the range B2:E2. We set thenextCellvariable to the first empty cell that is found, orNothingif no empty cells are found. If an empty cell is found, we select it. Finally, we enable events and exit the subroutine.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.