VBA + Run on a particular sheet + Excel workbook

I have an excel workbook. It has 3 sheets.

sheet 1 = “Status”
sheet 2 = “Report”
sheet 3 = “Template”

I want the below vb script to run only on sheet 2 that is “Report” sheet. How do I achieve that.

Function FindLastColoredCell()
'PURPOSE: Determine Last Cell On Sheet Containing Specific Fill Color

Dim TargetColor As Long
Dim cell As Range
Dim sht As Worksheet
Dim x As Long
Dim lastColoredCell As String

'Choose target color based on currently selected cell
TargetColor = 15132391

'Inversely Loop Through Each Cell In Used Range on ActiveSheet
For x = ActiveSheet.UsedRange.Cells.Count To 1 Step -1
If ActiveSheet.UsedRange.Cells(x).Interior.Color = TargetColor Then
'Notify User of Cell Address [Option 1]
'MsgBox "Last Color Found: " & ActiveSheet.UsedRange.Cells(x).Address
lastColoredCell = cstr(ActiveSheet.UsedRange.Cells(x).Address)

  'Select the last cell [Option 2]
    ActiveSheet.UsedRange.Cells(x).Select
 
  'Scroll To The Last Cell [Option 3]
    ActiveWindow.ScrollColumn = ActiveSheet.UsedRange.Cells(x).Column
    ActiveWindow.ScrollRow = ActiveSheet.UsedRange.Cells(x).Row
 
  'Exit Loop
    FindLastColoredCell = lastColoredCell
    Exit Function
End If

Next x

End Function @argin.lerit @ppr @Yoichi

@Sairam_RPA - You can add Sheets("Report").Activate like this:

Function FindLastColoredCell()
'PURPOSE: Determine Last Cell On Sheet Containing Specific Fill Color

Sheets("Report").Activate

Dim TargetColor As Long
Dim x As Long
Dim lastColoredCell As String

'Choose target color based on currently selected cell
TargetColor = 15132391

'Inversely Loop Through Each Cell In Used Range on ActiveSheet
For x = ActiveSheet.UsedRange.Cells.Count To 1 Step -1
	If ActiveSheet.UsedRange.Cells(x).Interior.Color = TargetColor Then
	'Notify User of Cell Address [Option 1]
	'MsgBox "Last Color Found: " & ActiveSheet.UsedRange.Cells(x).Address
	lastColoredCell = cstr(ActiveSheet.UsedRange.Cells(x).Address)

	  'Select the last cell [Option 2]
		ActiveSheet.UsedRange.Cells(x).Select
	 
	  'Scroll To The Last Cell [Option 3]
		ActiveWindow.ScrollColumn = ActiveSheet.UsedRange.Cells(x).Column
		ActiveWindow.ScrollRow = ActiveSheet.UsedRange.Cells(x).Row
	 
	  'Exit Loop
		FindLastColoredCell = lastColoredCell
		Exit Function
	End If
Next x

End Function
1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.