JasonEnsor
Programmer
Hi Guys,
I've been playing around with some code and can't quite figure out what i am doing wrong. My code SHOULD prompt the user for a search string, from that it will check if a worksheet exists, if so it will delete it (so all data is gone). it will create a new sheet named from the search string. it should then move that sheet to the end of the workbook. For every occurence of the search string in sheet1 it should copy that row in to the newly created sheet.
I am using this as a temporary summary of data on a user.
If i remove the code to add/delete a new sheet and move it to the end the whole thing works, creating a summary on sheet 2.
Any thoughts and ideas would be appreciated
Regards
J.
I've been playing around with some code and can't quite figure out what i am doing wrong. My code SHOULD prompt the user for a search string, from that it will check if a worksheet exists, if so it will delete it (so all data is gone). it will create a new sheet named from the search string. it should then move that sheet to the end of the workbook. For every occurence of the search string in sheet1 it should copy that row in to the newly created sheet.
I am using this as a temporary summary of data on a user.
If i remove the code to add/delete a new sheet and move it to the end the whole thing works, creating a summary on sheet 2.
Code:
Option Explicit
Sub SearchString()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim User_SearchString As String
Dim sh As Worksheet
On Error GoTo Err_Execute
LSearchRow = 2
LCopyToRow = 2
User_SearchString = InputBox("Enter Search String")
Set sh = Worksheets(User_SearchString)
If (WorksheetExists(User_SearchString)) = True Then
Application.DisplayAlerts = True
sh.Delete
End If
Worksheets.Add.Name = User_SearchString
Sheets(User_SearchString).Move AFTER:=Sheets(Sheets.Count)
Application.DisplayAlerts = True
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
If (StrComp(Range("B" & CStr(LSearchRow)).Value, User_SearchString, vbTextCompare) = 0) Then
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
Sheets(User_SearchString).Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
LCopyToRow = LCopyToRow + 1
Sheets("Sheet1").Select
End If
LSearchRow = LSearchRow + 1
Wend
Application.CutCopyMode = False
Range("A3").Select
MsgBox "All Complete"
Exit Sub
Err_Execute:
MsgBox "Error"
End Sub
Public Function WorksheetExists(ByVal WorksheetName As String) As Boolean
On Error Resume Next
WorksheetExists = (Sheets(WorksheetName).Name <> "")
On Error GoTo 0
End Function
Any thoughts and ideas would be appreciated
Regards
J.