Stop Excel from jumping to top after filtering/sorting - vba

I had the simple problem that Excel always jumped to the top after a macro ran automatically. Whenever I did a change in any cell the macro runs. However, after finishing, Excel jumps to the top. I want to stay where I edited the cell. I know there are multiple ways to fix this. My solution was one of the following.
Here my code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Selec, LastRow, LastCol, r As Integer
Dim rng As Range
Set Selec = Range(Target.Address)
LastCol = Range("XFD1").End(xlToLeft).Column
If Selec.Row > Range("A" & Rows.Count).End(xlUp).Row Then
LastRow = Selec.Row
Cells(Selec.Row, 1).value = Application.WorksheetFunction.Max(Range(Cells(1, 1), Cells(Selec.Row - 1, 1))) + 1
With Cells(Selec.Row, 4).Validation
.Delete
.Add Type:=xlValidateList, Operator:=xlBetween, Formula1:="=Parameters!$A$1:$A$3"
End With
Cells(Selec.Row, 4).value = "Not Started"
Else: LastRow = Range("A" & Rows.Count).End(xlUp).Row
End If
Set rng = Range(Cells(1, 1), Cells(LastRow, LastCol))
If Not Application.Intersect(rng, Selec) Is Nothing Then
For r = 2 To LastRow
Select Case Cells(r, 4)
Case "Completed"
Range(Cells(r, 1), Cells(r, LastCol)).Interior.Color = RGB(146, 208, 80)
Case "Not Started"
Range(Cells(r, 1), Cells(r, LastCol)).Interior.Color = RGB(255, 255, 255)
Case "In Progress"
Range(Cells(r, 1), Cells(r, LastCol)).Interior.Color = RGB(255, 255, 0)
End Select
If IsEmpty(Range(Cells(r, 1), Cells(r, LastCol))) = False Then
With Range("A" & r & "," & "C" & r & "," & "D" & r)
.HorizontalAlignment = xlCenter
End With
With Range("B" & r & "," & "E" & r & "," & "F" & r)
.WrapText = True
.HorizontalAlignment = xlLeft
End With
End If
Next r
End If
'Show Only In Progress and Not Started
Worksheets("Task List").Range("A1").AutoFilter Field:=4, Criteria1:=Array("In Progress", "=", "Not Started"), Operator:=xlFilterValues
'Worksheets("Task List").AutoFilter.Sort.SortFields.Add Key:=Range("C1" & Range("C" & Rows.Count).End(xlUp).Row), SortOn:=xlSortOnValues, Order:=xlAscending
Worksheets("Task List").AutoFilter.Sort.SortFields.Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending
With Worksheets("Task List").AutoFilter.Sort
.Header = xlYes
.Apply
End With
//Without one of the following lines Excel jumps to the top, but I want to stay at the end/selected cell. Uncommenting one of the following three lines solves this problem.
'Range(Target.Address).Select
'Selection.Select
'Selection.Activate
End Sub

It seems like that the jumping up is a side effect of filtering or sorting. To prevent Excel to jump up just add the following code at the end:
Target.Select
The following two lines of code work too, but are not recommended:
Selection.Select
or
Selection.Activate
All of them should prevent Excel to jump to the top and go back to current selection.

Try this good sir! This makes a temporary view (called "TempView") at the beginning of the code, then shows that view at the end and then immediately deletes this same view.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Selec, LastRow, LastCol, r As Integer
Dim rng As Range
ActiveWorkbook.CustomViews.Add ViewName:="TempView", PrintSettings:=True, _
RowColSettings:=True
Set Selec = Range(Target.Address)
LastCol = Range("XFD1").End(xlToLeft).Column
If Selec.Row > Range("A" & Rows.Count).End(xlUp).Row Then
LastRow = Selec.Row
Cells(Selec.Row, 1).Value = Application.WorksheetFunction.Max(Range(Cells(1, 1), Cells(Selec.Row - 1, 1))) + 1
With Cells(Selec.Row, 4).Validation
.Delete
.Add Type:=xlValidateList, Operator:=xlBetween, Formula1:="=Parameters!$A$1:$A$3"
End With
Cells(Selec.Row, 4).Value = "Not Started"
Else: LastRow = Range("A" & Rows.Count).End(xlUp).Row
End If
Set rng = Range(Cells(1, 1), Cells(LastRow, LastCol))
If Not Application.Intersect(rng, Selec) Is Nothing Then
For r = 2 To LastRow
Select Case Cells(r, 4)
Case "Completed"
Range(Cells(r, 1), Cells(r, LastCol)).Interior.Color = RGB(146, 208, 80)
Case "Not Started"
Range(Cells(r, 1), Cells(r, LastCol)).Interior.Color = RGB(255, 255, 255)
Case "In Progress"
Range(Cells(r, 1), Cells(r, LastCol)).Interior.Color = RGB(255, 255, 0)
End Select
If IsEmpty(Range(Cells(r, 1), Cells(r, LastCol))) = False Then
With Range("A" & r & "," & "C" & r & "," & "D" & r)
.HorizontalAlignment = xlCenter
End With
With Range("B" & r & "," & "E" & r & "," & "F" & r)
.WrapText = True
.HorizontalAlignment = xlLeft
End With
End If
Next r
End If
'Show Only In Progress and Not Started
Worksheets("Task List").Range("A1").AutoFilter Field:=4, Criteria1:=Array("In Progress", "=", "Not Started"), Operator:=xlFilterValues
'Worksheets("Task List").AutoFilter.Sort.SortFields.Add Key:=Range("C1" & Range("C" & Rows.Count).End(xlUp).Row), SortOn:=xlSortOnValues, Order:=xlAscending
Worksheets("Task List").AutoFilter.Sort.SortFields.Add Key:=Range("C:C"), SortOn:=xlSortOnValues, Order:=xlAscending
With Worksheets("Task List").AutoFilter.Sort
.Header = xlYes
.Apply
End With
ActiveWorkbook.CustomViews("TempView").Show
ActiveWorkbook.CustomViews("TempView").Delete
End Sub

Related

Copy pasting the cells when they are equal to another spreadsheet using Macro

I have a work question and i want my macro to do the following
i have two columns (column A and B). Column A has the names and column B contains their info.
I want my macro to find duplicate names and copy both col A and B and paste them into another spreadsheet in the following location
C:\Users\kentan\Desktop\Managed Fund
Each spreadsheet created must contain the name of that name as the file name
I have create the macro to do the following but it's not giving me the right result
Sub IRIS()
Dim i As Integer
With ActiveSheet.Sort
.SetRange Range("A:B")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlStroke
.Apply
End With
i=1
Do Until Len(Cells(i, 1).Value) = 0
If Cells(i, 1).Value = Cells(i + 1, 1).Value Then
Range(Cells(i, 1), Cells(i, 2)).Select
Selection.Copy
Workbooks.Add
Range("A1").PasteSpecial
ActiveWorkbook.SaveAs Filename:= _
"C:\Users\kentan\Desktop\Managed Fund" & cells(i,1) & ".xls"
ActiveWorkbook.Close
Else
i = i + 1
End If
Loop
Application.CutCopyMode = False
End Sub
Given the repetitious action of adding multiple workbooks, I would shovel that operation to a 'helper' sub.
Option Explicit
Public Const strSA As String = "C:\Users\kentan\Desktop\Managed Fund "
Sub iris()
Dim i As Long
With ActiveSheet
With .Range(.Cells(1, "A"), .Cells(.Rows.Count, "A").End(xlUp).Offset(0, 1))
.Sort key1:=.Columns(1), order1:=xlAscending , _
key2:=.Columns(2), order2:=xlAscending , _
Header:=xlYes, MatchCase:=False, _
Orientation:=xlTopToBottom, SortMethod:=xlStroke
End With
For i = 2 To .Rows.Count
If LCase(.Cells(i, "A").Value2) = LCase(.Cells(i - 1, "A").Value2) And _
LCase(.Cells(i, "A").Value2) <> LCase(.Cells(i + 1, "A").Value2) Then
newiris .Cells(i, "A").Value2, .Cells(i, "B").Value2
End If
Next i
End With
End Sub
Sub newiris(nm As String, nfo As String)
Application.DisplayAlerts = false
With Workbooks.Add
Do While .Worksheets.Count > 1: .Worksheets(2).Delete: Loop
.Worksheets(1).Cells(1, "A").Resize(1, 2) = Array(nm, nfo)
.SaveAs filename:=strSA & nm, FileFormat:=xlOpenXMLWorkbook
.Close savechanges:=False
End With
Application.DisplayAlerts = true
End Sub

excel vba code corrupting my file consistently after a few runs

I have a relatively long set of subs that get run on a list of my excel files a few times a day. after a few runs, the file then becomes corrupted which normally would not be an issue b/c it doesn't really effect any of the data. however, I have another program that opens up each of the excel and pulls some key data from each one to make a summary sheet. because the corrupted file gives a message that says something along the lines of "there is a problem with some of your content" the summary program stops with a
run-time error '1004': Method of object 'Workbooks' Failed
I can not for the life of me figure out what in my code is causing the corruption. Is there a way I can have the summary code ignore the corruption notification? Ive tried a handful of different things including turning the application notifications off in my code to no avail.
Any help is greatly appreciated! ill post my all my code with a brief description below:
Here is the code from the summary file that opens each of the
individual files and pulls data:
Sub OEEsummmary()
Dim ActCycCell, ExpCycCell, ExpCurCycCell, ShiftCell, DifCell, DownCell, DTResACell, DTResBCell, PartCell, OpNamCell, OprCell, RejCell, RejResCell As Range
Dim MySheet As Worksheet
Dim Txt$, MyPath$, MyWB$
Dim myValue As Integer
Dim x As Long
Dim v As Variant, r As Range, rWhere As Range
MyPath = "L:\Manufacturing Engineering\Samuel Hatcher\"
x = 2
Set MySheet = ActiveSheet
'Application.ScreenUpdating = False
Application.EnableEvents = False
MySheet.Range("B2:G18").ClearContents
MySheet.Range("J2:O18").ClearContents
Do While MySheet.Range("A" & x).Value <> ""
MyWB = MySheet.Range("A" & x).Text
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
Set ActCycCell = ActiveSheet.Range("E21")
Set ExpCycCell = ActiveSheet.Range("D21")
Set ShiftCell = ActiveSheet.Range("E2")
Set DownCell = ActiveSheet.Range("K28")
Set DTResACell = ActiveWorkbook.Worksheets("Downtime").Range("O9")
Set DTResBCell = ActiveWorkbook.Worksheets("Downtime").Range("O10")
Set PartCell = ActiveSheet.Range("E4")
Set ExpCurCycCell = ActiveSheet.Range("D22")
If ActiveSheet.Range("I3") = "" Then
Set OpNamCell = ActiveSheet.Range("I2")
Else
Set OpNamCell = ActiveSheet.Range("I3")
End If
Set OprCell = ActiveSheet.Range("C4")
Set RejCell = ActiveSheet.Range("H21")
Set RejResCell = ActiveWorkbook.Worksheets("Rejected Parts").Range("H5")
With MySheet.Range("A" & x)
.Offset(0, 14).Value = OprCell.Value
.Offset(0, 13).Value = OpNamCell.Value
.Offset(0, 12).Value = PartCell.Value
.Offset(0, 11).Value = ShiftCell.Value
.Offset(0, 10).Value = RejResCell.Value
.Offset(0, 9).Value = RejCell.Value
.Offset(0, 6).Value = ActCycCell.Value
.Offset(0, 5).Value = ExpCycCell.Value
.Offset(0, 4).Value = ExpCurCycCell.Value
.Offset(0, 3).Value = DTResBCell.Value
.Offset(0, 2).Value = DTResACell.Value
.Offset(0, 1).Value = DownCell.Value
End With
ActiveWorkbook.Close savechanges:=False
x = x + 1
Loop
Call sort
'Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Clears the page of data to prepare it for a new shift of entering
data:
Sub ClearFrontEnd()
Sheets("Front End").Unprotect ("29745")
'prompts user to confirm if they realy want to clear entry
response = MsgBox("Are You Sure?", vbYesNo)
If response = vbNo Then
Exit Sub
End If
'checks to see if operator number is there
If range("I3").Value = "" Then
MsgBox "ENTER OPORATOR # AND CLICK NEW SHIFT AGAIN"
Else
Call StopTimer
Call prodChoose
Call transfer
Application.ScreenUpdating = False
ActiveWorkbook.Save
Sheets("Front End").Unprotect ("29745")
Sheets("Front End").Select
'Deletes the data from the entry and unique key fields
range("E8:E20").ClearContents
range("I8:I27").ClearContents
range("J8:J27").ClearContents
range("K8:K27").ClearContents
range("I3").ClearContents
range("H8").Value = ""
range("H9").Value = ""
range("H10").Value = ""
range("H11").Value = ""
range("H12").Value = ""
range("H13").Value = ""
range("H14").Value = ""
range("H15").Value = ""
range("H16").Value = ""
range("H17").Value = ""
range("H18").Value = ""
range("H19").Value = ""
range("H20").Value = ""
range("A1").Select
MsgBox "Please enter the correct values for SHIFT #, SHIFT LENGTH, PART #, AND OPORATOR #, Thanks! Have a great day!!"
End If
Sheets("Front End").Protect ("29745")
Call timerchoose
Application.ScreenUpdating = True
End Sub
This copies the data from the front page to a raw data sheet every
hour:
Sub transfer()
Sheets("Front End").Unprotect ("29745")
Application.ScreenUpdating = False
Dim x As Long
Dim v As Variant, r As range, rWhere As range
'set starting point at row 8
x = 8
'defines the sheet the data is being coppied from and pasted to
Dim sourceSheet As Worksheet: Set sourceSheet = ThisWorkbook.Worksheets("Front End")
Dim destSheet As Worksheet: Set destSheet = ThisWorkbook.Worksheets("Raw Data")
If sourceSheet.range("I3").Value = "" Then
Call StartTimer
Exit Sub
Else
Do While range("L" & x).Value <> ""
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("M" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("J" & x).Value
destSheet.range("C" & lMaxRows + 1).Value = sourceSheet.range("K" & x).Value
destSheet.range("D" & lMaxRows + 1).Value = sourceSheet.range("L" & x).Value
destSheet.range("E" & lMaxRows + 1).Value = sourceSheet.range("I" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("M" & x).Value
x = x + 1
Else
x = x + 1
End If
Loop
x = 8
Do While range("D" & x).Value <> 0
If range("E" & x).Value <> "" Then
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("A" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("B" & x).Value
destSheet.range("L" & lMaxRows + 1).Value = sourceSheet.range("C" & x).Value
destSheet.range("F" & lMaxRows + 1).Value = sourceSheet.range("D" & x).Value
destSheet.range("G" & lMaxRows + 1).Value = sourceSheet.range("E" & x).Value
destSheet.range("I" & lMaxRows + 1).Value = sourceSheet.range("G" & x).Value
destSheet.range("K" & lMaxRows + 1).Value = sourceSheet.range("H" & x).Value
destSheet.range("H" & lMaxRows + 1).Value = sourceSheet.range("N" & x).Value
destSheet.range("J" & lMaxRows + 1).Value = sourceSheet.range("O" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("A" & x).Value
x = x + 1
Else
x = x + 1
End If
Else
x = x + 1
End If
Loop
'sorts Raw Data table after new data is added
Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("Raw Data")
'specifies how to sort the data
With ws.Sort.SortFields
.Clear
.add Key:=ws.range("A2:A" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.add Key:=ws.range("B2:B" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
'specifies range over which to sort
End With
With ws.Sort
.SetRange ws.range("A1:S" & lMaxRows + 1)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Sheets("Front End").Protect ("29745")
Call SortDTWeek
Call SortDTMonth
Call StartTimer
Application.ScreenUpdating = True
End Sub
This checks a few cells constantly to see if they have been double
clicked, if so it puts the current time in that cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As range, cancel As Boolean)
'Adds downtime start and finish values
'Check to see if the click/selected cell is in columns I or J
If Not Intersect(Target, range("J:K")) Is Nothing Then
'Make sure cell is in range
If Target.Row > 7 And Target.Row <= 27 Then
'Update the value
Target.Value = Time()
End If
End If
End Sub
Checks to see if a set of cells has been changed, if so it puts the
now() value in a corresponding "key" column
Private Sub Worksheet_Change(ByVal Target As range)
Sheets("Front End").Unprotect ("29745")
Dim cell As range
'Adds unique keyA values
'Check to see if the changed cell is in column E
If Not Intersect(Target, range("E:E")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And Target.Row > 7 And Target.Row <= 20 Then
'Update the "KeyA" value
Sheets("Front End").range("A" & Target.Row).Value = Now()
End If
Next cell
Else
'Adds unique keyB values
'Check to see if the changed cell is in column K
If Not Intersect(Target, range("K:K")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And (Target.Row > "6" And Target.Row <= "27") Then
'Update the "KeyM" value
range("M" & Target.Row).Value = Now()
End If
Next cell
End If
End If
Sheets("Front End").Unprotect ("29745")
End Sub
thanks for any input this issue has been driving me crazy
as #MLind suggested in the comments, to bypass the corrupted file error and pull some data out i added this to my code:
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True,
CorruptLoad:=xlExtractData
and used
Application.DisplayAlerts = False
within the loop to prevent any pop up boxes from stopping the sub

VBA Selecting cells when it shouldn't with IF Range.Text = "True"?

I have the following code, which is a work in progress, but VBA keeps saying the If Range("G"&CRow).text = "True" then is true in the highlighted row, when it obviously isn't. Can anyone help me figure this out?
Range("G1").FormulaR1C1 = _
"=IF(OR(ISNUMBER(SEARCH(""GS "",RC[-6])),ISNUMBER(SEARCH(""#"",RC[-6]))),""TRUE"",""FALSE"")"
Range("G1").AutoFill Destination:=Range("G1:G" & lastrow)
With Range("G1:G" & lastrow)
.Value = .Value
End With
Dim T As Integer
Dim CRow As Integer
CRow = 1
For Each cell In Range("G1:G" & lastrow)
If Range("G" & CRow).Text = "TRUE" Then
cell.Select
ActiveCell.Offset(0, -5).Select
If Selection.Value = "" Then
Selection.Resize(, 4).Select
Selection.Delete Shift:=xlUp
ActiveCell.Offset(2, 0).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
CRow = CRow - 1
End If
Else
CRow = CRow + 1
End If
Next
BECAUSE of this
CRow = 1
For Each cell In Range("G1:G" & lastrow)
If Range("G" & CRow).Text = "TRUE" Then
You are assiging 1 to CRow and using that in each iteration. So actually you are always testing Just Row 1.
Change Range("G" & CRow).Text to cell.Text
See below example to delete the same group of cells using a reverse loop and not selecting. I believe I interpreted, and thus changed, this line properly ActiveCell.Offset(2, 0).Select, but let me know if I'm mistaken and it doesn't function as expected.
Range("G1").FormulaR1C1 = _
"=IF(OR(ISNUMBER(SEARCH(""GS "",RC[-6])),ISNUMBER(SEARCH(""#"",RC[-6]))),""TRUE"",""FALSE"")"
Range("G1").AutoFill Destination:=Range("G1:G" & lastrow)
With Range("G1:G" & lastrow)
.Value = .Value
End With
Dim T As Integer
For T = 1 to lastrow Step -1
Set cell = Range("G" & T)
If cell.Text = "TRUE" Then
If cell.offset(0,-5) = "" Then
cell.Offset(0,-5).Resize(,4).Delete Shift=xlUp
Range("G" & T + 2).Insert Shift:=xlDown CopyOrigin:=xlFormatFromLeftOrAbove
End If
End If
Next

Excel Macro: Copy data into new worksheet and sort base on date and random number

For the following excel data:
1 Name Date Color_picked
2 John 8/1/2015 Red
3 Jason 8/13/2015 Blue
4 Kevin 8/12/2015 Yellow
5 Derek 8/13/2015 Blue
6 Cherry 8/1/2015 Red
I want to do the follow:
1) Generate a random number for each of row (Not including the title row)
2) Copy all the records into a new tab/worksheet base on the color(Red, Blue and Yellow tabs)
3) Within each new tabs (Red, Blue and Yellow tabs), first sort the record by the date, if deplicated date, then sort by the random number.
This is what I have so far:
Sub myFoo()
Application.CutCopyMode = False
On Error GoTo Err_Execute
Sheet1.Range("B1:F3").Copy
Red.Range("A1").Rows("1:1").Insert Shift:=xlDown
Err_Execute:
If Err.Number = 0 Then MsgBox "Transformation Done!" Else _
MsgBox Err.Description
End Sub
Should I be creating the copy first or sort first?
This should do the trick :
Sub test_Ryan_Fung()
Dim WsSrc As Worksheet, _
WsRed As Worksheet, _
WsBlue As Worksheet, _
WsYellow As Worksheet, _
Ws As Worksheet, _
DateFilterRange As String, _
RandomRange As String, _
TotalRange As String, _
LastRow As Long, _
WriteRow As Long, _
ShArr(), _
Arr()
Set WsSrc = Sheet1
Set WsRed = Sheets("Red")
Set WsBlue = Sheets("Blue")
Set WsYellow = Sheets("Yellow")
ReDim ShArr(1 To 3)
Set ShArr(1) = WsRed: Set ShArr(2) = WsBlue: Set ShArr(3) = WsYellow
Application.CutCopyMode = False
On Error GoTo Err_Execute
With WsSrc
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To LastRow
.Cells(i, 5) = Application.WorksheetFunction.RandBetween(1, 10000)
Next i
Arr = .Range("A2:E" & LastRow).Value
End With
For i = LBound(Arr, 1) To UBound(Arr, 1)
Select Case LCase(Arr(i, 4))
Case Is = "red"
With WsRed
WriteRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
For j = LBound(Arr, 2) To UBound(Arr, 2)
.Cells(WriteRow, j) = Arr(i, j)
Next j
End With
Case Is = "blue"
With WsBlue
WriteRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
For j = LBound(Arr, 2) To UBound(Arr, 2)
.Cells(WriteRow, j) = Arr(i, j)
Next j
End With
Case Is = "yellow"
With WsYellow
WriteRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
For j = LBound(Arr, 2) To UBound(Arr, 2)
.Cells(WriteRow, j) = Arr(i, j)
Next j
End With
Case Else
MsgBox "Color not recognised : " & Arr(i, 4), vbCritical + vbOKOnly
End Select
Next i
For i = LBound(ShArr, 1) To UBound(ShArr, 1)
Set Ws = ShArr(i)
With Ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
DateFilterRange = "C2:C" & LastRow
RandomRange = "E2:E" & LastRow
TotalRange = "A1:E" & LastRow
With .Sort
With .SortFields
.Clear
.Add Key:=Range(DateFilterRange), _
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
.Add Key:=Range(RandomRange), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
End With
.SetRange Range(TotalRange)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
Next i
Err_Execute:
If Err.Number = 0 Then
MsgBox "Transformation Done!"
Else
MsgBox Err.Description
End If
End Sub

How to find the cell next to active cell in excel

I want to create a log file in excel.
I have created a macro that will insert in-time into active cell on ButtonInTime click. Similarly out time in the active cell on ButtonOutTime click...
Now i want to insert todays date on ButtonInTime click in previous cell of active cell
and
calculate Total Log hours & insert it into next active cell of OutTime.
How i can achive this?
Can any one help me out???
I tried to find out the solution, but didnt get the proper one...
Thanks in advance....
I achieved it.. There are some hard codes in this....
Sub ButtonInTime_Click()
Range("A1").End(xlDown).Select
activecell.Offset(1, 0).Select
activecell.Value = Date
activecell.Offset(0, 1).Value = Time()
activecell.Offset(0, 3).Interior.Color = RGB(255, 0, 0)
activecell.Offset(0, 3).Value = "Log Not Closed!!!"
Range("A" & activecell.Row & ":E" & activecell.Row).Borders(xlEdgeTop).LineStyle = xlContinuous
Range("A" & activecell.Row & ":E" & activecell.Row).Borders(xlEdgeRight).LineStyle = xlContinuous
Range("A" & activecell.Row & ":E" & activecell.Row).Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("A" & activecell.Row & ":E" & activecell.Row).Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B" & activecell.Row).Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C" & activecell.Row).Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D" & activecell.Row).Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E" & activecell.Row).Borders(xlEdgeRight).LineStyle = xlContinuous
End Sub
Sub ButtonOutTime_Click()
Range("C1").End(xlDown).Select
activecell.Offset(1, 0).Select
activecell.Value = Time()
activecell.Offset(0, 1).Value = activecell.Value - activecell.Offset(0, -1).Value
activecell.Offset(0, 1).Interior.Color = RGB(255, 255, 255)
End Sub