This VBA code also has a Function. Have I written it correctly: Sub CopyPRtoEvents() Dim…
- User
This VBA code also has a Function. Have I written it correctly: Sub CopyPRtoEvents() Dim prtodayWorkbook As Workbook Set prtodayWorkbook = Workbooks("Premises Requests") Dim serviceprovidersWorkbook As Workbook Set serviceprovidersWorkbook = Workbooks("Service Providers")
Dim prtodaySheet As Worksheet Set prtodaySheet = ThisWorkbook.Sheets("PRtoday") Dim selectedRow As Range Set selectedRow = Selection.EntireRow Dim prtodayRange As Range Set prtodayRange = prtodaySheet.Range("B" & selectedRow.Row & ":D" & selectedRow.Row)
If Not IsWorkbookOpen("Service Providers") Then MsgBox "Workbook 'Service Providers' not open" Exit Sub End If
Dim eventsSheet As Worksheet 'Set eventsSheet = Workbooks("Service Providers.xlsm").Sheets("Events") Set eventsSheet = serviceprovidersWorkbook.Sheets("Events")
serviceprovidersWorkbook.Activate eventsSheet.Select
Dim lastRow As Long lastRow = eventsSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
eventsSheet.Range("B" & lastRow).Value = prtodaySheet.Range("D" & selectedRow.Row).Value eventsSheet.Range("C" & lastRow).Value = prtodaySheet.Range("C" & selectedRow.Row).Value eventsSheet.Range("D" & lastRow).Value = prtodaySheet.Range("B" & selectedRow.Row).Value
prtodayWorkbook.Activate prtodayWorkbook.Sheets("PRtoday").Select
MsgBox "Request successfully copied to Events."
End Sub
Function IsWorkbookOpen(wbName As String) As Boolean Dim wb As Workbook On Error Resume Next Set wb = Workbooks(wbName & ".xlsm") IsWorkbookOpen = Not wb Is Nothing End Function
- Assistant
Yes, the Function IsWorkbookOpen() has been written correctly. It takes in a parameter wbName and returns a boolean value indicating whether there is a workbook with the specified name currently open or not. It achieves this by attempting to set the variable 'wb' to the specified workbook name, and then checking if it is Nothing (i.e., if the workbook is not open, 'wb' will not be set and will therefore be Nothing). The On Error Resume Next statement ensures that if there is an error setting 'wb' (e.g., if the workbook name is invalid or not found), the code does not halt and returns False by default.