Sheets(Target.Value).Activate End If Dim sheetName As String Dim rowValues As String Dim…
- User
Sheets(Target.Value).Activate End If
Dim sheetName As String Dim rowValues As String Dim FilePath As String Dim ws As Worksheet Dim lastrow As Long Dim i As Integer
'check if selection is in column A If Target.Column <> 1 Or IsEmpty(Me.Range("D" & Target.Row)) Then Exit Sub Application.EnableEvents = True 'get sheet name from selected cell in column D sheetName = Me.Range("D" & Target.Row).Value
'get last non-blank row in column J of the sheet Set ws = ThisWorkbook.Sheets(sheetName) lastrow = ws.Cells(Rows.Count, "J").End(xlUp).Row
'get values from the last row For i = 1 To 10 'A-J rowValues = rowValues & ws.Cells(lastrow, i).Value & "," Next i rowValues = Left(rowValues, Len(rowValues) - 1) 'remove last comma
'create text file with row values FilePath = "G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\LastJob.txt" 'replace with your desired file path 'Open FilePath For Output As #1 'Print #1, rowValues 'Close #1
Open FilePath For Output As #1 For i = 1 To 10 'A-J Print #1, ws.Cells(lastrow, i).Value Next i Close #1
'open text file Shell "notepad.exe " & FilePath, vbNormalFocus 'replace notepad.exe with your preferred text editor End Sub
Occassionaly when I return to this sheet from another sheet i get an error on
Set ws = ThisWorkbook.Sheets(sheetName)
What is the cause of this error and how do I stop it
- Assistant
The error may be caused by the sheet name not being recognized, possibly due to a typo or the sheet being renamed. To prevent the error, you can add error handling to the code to check if the sheet name exists before trying to set the worksheet variable.
Here's an example of how to modify the code:
'check if selection is in column A If Target.Column <> 1 Or IsEmpty(Me.Range("D" & Target.Row)) Then Exit Sub Application.EnableEvents = True 'get sheet name from selected cell in column D sheetName = Me.Range("D" & Target.Row).Value
'check if sheet name exists On Error Resume Next Set ws = ThisWorkbook.Sheets(sheetName) If ws Is Nothing Then MsgBox sheetName & " sheet does not exist.", vbExclamation Exit Sub End If On Error GoTo 0
'get last non-blank row in column J of the sheet lastrow = ws.Cells(Rows.Count, "J").End(xlUp).Row
'continue with rest of the code...
This code uses "On Error Resume Next" to temporarily ignore any errors that might occur when trying to set the worksheet variable. If the sheet doesn't exist, the variable "ws" will be set to "Nothing". The code then checks if "ws" is still "Nothing", and if so, displays an error message and exits the subroutine. Finally, the code turns off error handling with "On Error GoTo 0" and continues with the rest of the code.