How to locate all '0' on fixed row and varying Columns, then sum them up? - vba

I need help with my code, I'm not sure why it isnt running properly and takes a very long time. What i'm trying to do is to locate repeated temp, for example, 0. After locating 0, I will continue to look for any more 0 at the temp row, if there is i will sum the test1 of B3 and test1 of H3 together... it will continue until the end of the row and will be pasted at Column N or O which is an empty column. After that, will have to do the same for 100, overall.
The resultant should be like this
I have trouble running the following code that i tried writing.
Dim temprow As Long, ColMax1 As Long, tempcell As Range, ColCount1 As Long
Dim temprow1 As Long, valuetohighlight As Variant, valuetohighlight1 As Variant
Dim totalvalue As Double, findvalues As Long
temprow = 1
ColMax1 = 10
Do
Set tempcell = Sheets("Sheet1").Cells(temprow, 1)
'Look for the word temp in column A
If tempcell = "temp" Then
'Look for values = 0
For ColCount1 = 2 To ColMax1
findvalues = Sheets("Sheet1").Cells(temprow, ColCount1)
If findvalues = 0 Then
temprow1 = temprow + 1
valuetohighlight = Sheets("Sheet1").Cells(temprow1, ColCount1)
End If
Next
'Look for other values that is equal to 0
For ColCount1 = 3 To ColMax1
findvalues = Sheets("Sheet1").Cells(temprow, ColCount1)
If findvalues = 0 Then
temprow1 = temprow + 1
valuetohighlight1 = Sheets("Sheet1").Cells(temprow1, ColCount1)
End If
Next
temprow = temprow + 1
End If
Loop
For ColCount1 = 1 To ColMax1
If Sheets("Sheet1").Cells(temprow, ColCount1) = "" Then
totalvalue = 0
totalvalue = valuetohighlight + valuetohighlight1
End If
Next
End Sub
If you have any ideas or opinion, do share it with me.. will appreciate your help!
Slight Modifications
Now need also to consider the name.

What you want to achieve can be done with a formula. The trick is to keep the Cell Headers in Col O to Q in Row 2 to actual values that you want to compare.
Formula in Cell O3
=SUMPRODUCT(($B$2:$M$2=$O$2)*B3:M3)
Snapshot
FOLLOW UP
Hi, i remember u using that formula and typed it into a VBA for me before, i have tried and it work.. Sheets("Sheet1").[O5] = Evaluate("SUMPRODUCT((B2:M2=O2)*(B5:M5))") but, i cant really have a fixed column for the printed result and also the temp may not falls on Row 2...
Here is a sample code. Change 15 to the relevant column where you want to display the result. I have commented the code so you shouldn't have any problem in understanding the code. If you still do then simply ask :)
CODE
Option Explicit
Sub Sample()
Dim ColNo As Long, tempRow As Long
Dim ws As Worksheet
Dim aCell As Range
'~~> Change this to the column number where you want to display the result
'~~> The code assumes that Row 2 in this column has headers
'~~> for which you want to retrieve values
ColNo = 18 '<~~ Example :- Column R
'~~> Change this to relevant sheet name
Set ws = Sheets("Sheet1")
'~~> Get the row number which has "Temp"
Set aCell = ws.Columns(1).Find(What:="Temp", LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
'~~> This is the row which has 'Temp'
tempRow = aCell.Row
'~~> Sample for putting the value in Row 3 (assuming that 'temp' is not in row 3)
'~~> SNAPSHOT 1
ws.Cells(3, ColNo).Value = Evaluate("=SUMPRODUCT(($B$" & tempRow & ":$M$" & tempRow & "=" & _
ws.Cells(2, ColNo).Address & ")*(B3:M3))")
'~~> If you want to use formula in the cell in lieu of values then uncomment the below
'~~> SNAPSHOT 2
'ws.Cells(3, ColNo).Formula = "=SUMPRODUCT(($B$" & tempRow & ":$M$" & tempRow & "=" & _
ws.Cells(2, ColNo).Address & ")*(B3:M3))"
Else
MsgBox "Temp Not Found. Exiting sub"
End If
End Sub
SNAPSHOT (IF YOU USE EVALUATE IN THE ABOVE CODE)
SNAPSHOT (IF YOU USE .FORMULA IN THE ABOVE CODE)
HTH
Sid

Related

Finding first previous 0 from starting cell

I'm trying to count the number of cells between two cells that I need to find with vba. The first cell is going to be in the same column as the current date today. The column headers are left to right in date order (May 1st, May 2nd, May 3rd, etc..). Once I find the column to begin with, I need to count the number of cells backwards that contain 0 until I find a cell without a 0. So say I'm starting in column U, I need to count the number of contiguous cells with 0 until say column R has a 1. My answer would then be 2 because columns T and S had 0's.
The issue I'm running into with the below code is that I'm trying to find first the column I'm supposed to be in based on the date (This part works). Next I'm declaring the rowNum as the activecell row number (This part work). Next I need to find which column to count backwards to (This part does not work). I'm getting the same column number on the colNum FIND code as I am the colStart FIND code.
I'm not getting any errors, it just doesn't seem like it's finding the previous cell with 0 and is instead just giving me the same column. I hope this is clear. Let me know if you need any additional info. Thanks everyone!
today = Date
colNum = Cells.Find(today, searchorder:=xlByRows,
searchdirection:=xlPrevious).Column
rowNum = ActiveCell.Row
colStart = Cells.Find(0, after:=Cells(rowNum, colNum),
searchorder:=xlByColumns, searchdirection:=xlPrevious).Column
Try this code:
Public Function countZeros(ws As Worksheet, rowNum As Long, colNum As Long, Optional stopColumn As Long = 1) As Long
Dim currentCol As Long
countZeros = 0
If colNum <= stopColumn Then Exit Function 'prevents going past a certain point (for example your label column)
For currentCol = colNum - 1 To stopColumn + 1 Step -1
If ws.Cells(rowNum, currentCol) = 0 Then
countZeros = countZeros + 1
Else
Exit Function
End If
Next 'currentCol
End Function
Public Sub mySub()
Dim colNum As Long
Dim rowNum As Long
Dim output As String
Dim today
Dim rng As Range
today = Date
Set rng = Cells.Find(today, searchorder:=xlByRows, searchdirection:=xlPrevious)
If rng Is Nothing Then
MsgBox "Did not find todays date, make sure your active cell is in the right location"
Exit Sub
End If
colNum = rng.Column
rowNum = ActiveCell.Row
output = "Total number of cells from " & Cells(rowNum, colNum).Address & " that have zeros: "
output = output & CStr(countZeros(ActiveWorkbook.ActiveSheet, rowNum, colNum))
MsgBox output
End Sub
With this data set:
you get the output:
Total number of cells from $K$7 that have zeros: 6

How To Have VBA Insert Formula Result as a Value

I got help last week getting my syntax and ranges correct, and thought I could just do a vlookup to finish it but apparently I was mistaken. It just seems like when I try to research how to accomplish this, I find various examples but I don't have the background to translate it to my code.
The macro runs and does almost everything its supposed to do. But in addition to inserting the arrays, there are 3 other cells that need values when there are blank cells in my ‘sourcerng’.
This is the logic for the cells that need values (the values are already in my worksheet, I just need to get them to these blank cells). I tried to do an IIF statement for these but I still have no idea what I'm doing. Would that be the best way? Should it just be another IF THEN statement?
rngBE - IF Column Z = 0 Then copy value from corresponding row in column O. Otherwise copy value from column Z
rngBG - IF Column AA = "Unknown" Then copy value from corresponding row in column I. Otherwise copy value from column AA.
rngBK - IF Column AB = "Unknown" Then copy value from corresponding row in column N. Otherwise copy value from column AB.
Sub AutomateAllTheThings6()
Dim arr3() As String
Dim arr11() As String
'Dim resBE As String
Dim rng3 As Range
Dim rng11 As Range
Dim rngBE As Range
Dim rngBG As Range
Dim rngBK As Range
Dim sourcerng As Range
'Dim firstRow As Long
Dim lastRow As Long
'Dim i As Long
Call OptimizeCode_Begin
'firstRow = 2
lastRow = ActiveSheet.Range("D1").End(xlDown).Row
Set rng3 = ActiveSheet.Range("BH2:BJ" & lastRow)
Set rng11 = ActiveSheet.Range("BL2:BV" & lastRow)
Set rngBE = ActiveSheet.Range("BE2:BE" & lastRow)
Set rngBG = ActiveSheet.Range("BG2:BG" & lastRow)
Set rngBK = ActiveSheet.Range("BK2:BK" & lastRow)
Set sourcerng = ActiveSheet.Range("BE2:BE" & lastRow)
arr3() = Split("UNKNOWN,UNKNOWN,UNKNOWN", ",")
arr11() = Split("UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,UNKNOWN,00/00/0000, _
00/00/0000,00/00/0000,00/00/0000,NEEDS REVIEW", ",")
For Each cell In sourcerng
If IsEmpty(cell) Then
Intersect(rng3, ActiveSheet.Rows(cell.Row)).Value = arr3
Intersect(rng11, ActiveSheet.Rows(cell.Row)).Value = arr11
'***PLS HELP***
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value = "WEEEEE"
Intersect(rngBG, ActiveSheet.Rows(cell.Row)).Value = "WOOOOO"
Intersect(rngBK, ActiveSheet.Rows(cell.Row)).Value = "WAAAAA"
End If
Next
Range("BR2:BU2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.NumberFormat = "mm/dd/yyyy"
Columns("BF:BF").Select
Selection.Delete Shift:=xlToLeft
Call OptimizeCode_End
End Sub
'*********TESTING***********
'resBE = IIf(Cells(13,Z).Value = 0, Cells(13,BE).Value = Cells(13,Z), Cells(13,BE).Value = Cells(13,O))
'***************************************
'For i = firstRow To lastRow
' valZ = Range("Z" & i)
' valOh = Range("O" & i)
'
' If valZ = 0 Then
' rngBE.Value = valOh
' Else rngBE.Value = valZ
' End If
There are several ways to do your task. If you're more of an "Excel" person than VBA you might consider this approach: You can inject the syntax of any "regular" formula in R1C1 Format.
So the formula mentioned above =if($Z2=0,$O2,$Z2) is .FORMULA format for any value in row 2.
But in .FORMULAR1C1 it can be inserted in ANY cell as: =IF(RC26=0,RC15,RC26) (basically no rows up or down, but always columns O (15) and Z(26).
So, your modified code would have something like this:
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).FormulaR1C1 = "=IF(RC26=0,RC15,RC26)"
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value = _
Intersect(rngBE, ActiveSheet.Rows(cell.Row)).Value
Again, this is NOT the most efficient way to accomplish your task, but if you're dealing with thousandsof rows, versus tens to hundreds of thousands, I wouldn't worry about it and it gives you a new tool to use.

How to embed a 'lastrow' in a VBA code [duplicate]

How can I find the last row that contains data in a specific column and on a specific sheet?
How about:
Function GetLastRow(strSheet, strColumn) As Long
Dim MyRange As Range
Set MyRange = Worksheets(strSheet).Range(strColumn & "1")
GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
End Function
Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:
Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
You should use the .End(xlup) but instead of using 65536 you might want to use:
sheetvar.Rows.Count
That way it works for Excel 2007 which I believe has more than 65536 rows
Simple and quick:
Dim lastRow as long
Range("A1").select
lastRow = Cells.Find("*",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row
Example use:
cells(lastRow,1)="Ultima Linha, Last Row. Youpi!!!!"
'or
Range("A" & lastRow).Value = "FIM, THE END"
function LastRowIndex(byval w as worksheet, byval col as variant) as long
dim r as range
set r = application.intersect(w.usedrange, w.columns(col))
if not r is nothing then
set r = r.cells(r.cells.count)
if isempty(r.value) then
LastRowIndex = r.end(xlup).row
else
LastRowIndex = r.row
end if
end if
end function
Usage:
? LastRowIndex(ActiveSheet, 5)
? LastRowIndex(ActiveSheet, "AI")
Public Function LastData(rCol As Range) As Range
Set LastData = rCol.Find("*", rCol.Cells(1), , , , xlPrevious)
End Function
Usage: ?lastdata(activecell.EntireColumn).Address
All the solutions relying on built-in behaviors (like .Find and .End) have limitations that are not well-documented (see my other answer for details).
I needed something that:
Finds the last non-empty cell (i.e. that has any formula or value, even if it's an empty string) in a specific column
Relies on primitives with well-defined behavior
Works reliably with autofilters and user modifications
Runs as fast as possible on 10,000 rows (to be run in a Worksheet_Change handler without feeling sluggish)
...with performance not falling off a cliff with accidental data or formatting put at the very end of the sheet (at ~1M rows)
The solution below:
Uses UsedRange to find the upper bound for the row number (to make the search for the true "last row" fast in the common case where it's close to the end of the used range);
Goes backwards to find the row with data in the given column;
...using VBA arrays to avoid accessing each row individually (in case there are many rows in the UsedRange we need to skip)
(No tests, sorry)
' Returns the 1-based row number of the last row having a non-empty value in the given column (0 if the whole column is empty)
Private Function getLastNonblankRowInColumn(ws As Worksheet, colNo As Integer) As Long
' Force Excel to recalculate the "last cell" (the one you land on after CTRL+END) / "used range"
' and get the index of the row containing the "last cell". This is reasonably fast (~1 ms/10000 rows of a used range)
Dim lastRow As Long: lastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row - 1 ' 0-based
' Since the "last cell" is not necessarily the one we're looking for (it may be in a different column, have some
' formatting applied but no value, etc), we loop backward from the last row towards the top of the sheet).
Dim wholeRng As Range: Set wholeRng = ws.Columns(colNo)
' Since accessing cells one by one is slower than reading a block of cells into a VBA array and looping through the array,
' we process in chunks of increasing size, starting with 1 cell and doubling the size on each iteration, until MAX_CHUNK_SIZE is reached.
' In pathological cases where Excel thinks all the ~1M rows are in the used range, this will take around 100ms.
' Yet in a normal case where one of the few last rows contains the cell we're looking for, we don't read too many cells.
Const MAX_CHUNK_SIZE = 2 ^ 10 ' (using large chunks gives no performance advantage, but uses more memory)
Dim chunkSize As Long: chunkSize = 1
Dim startOffset As Long: startOffset = lastRow + 1 ' 0-based
Do ' Loop invariant: startOffset>=0 and all rows after startOffset are blank (i.e. wholeRng.Rows(i+1) for i>=startOffset)
startOffset = IIf(startOffset - chunkSize >= 0, startOffset - chunkSize, 0)
' Fill `vals(1 To chunkSize, 1 To 1)` with column's rows indexed `[startOffset+1 .. startOffset+chunkSize]` (1-based, inclusive)
Dim chunkRng As Range: Set chunkRng = wholeRng.Resize(chunkSize).Offset(startOffset)
Dim vals() As Variant
If chunkSize > 1 Then
vals = chunkRng.Value2
Else ' reading a 1-cell range requires special handling <http://www.cpearson.com/excel/ArraysAndRanges.aspx>
ReDim vals(1 To 1, 1 To 1)
vals(1, 1) = chunkRng.Value2
End If
Dim i As Long
For i = UBound(vals, 1) To LBound(vals, 1) Step -1
If Not IsEmpty(vals(i, 1)) Then
getLastNonblankRowInColumn = startOffset + i
Exit Function
End If
Next i
If chunkSize < MAX_CHUNK_SIZE Then chunkSize = chunkSize * 2
Loop While startOffset > 0
getLastNonblankRowInColumn = 0
End Function
Here's a solution for finding the last row, last column, or last cell. It addresses the A1 R1C1 Reference Style dilemma for the column it finds. Wish I could give credit, but can't find/remember where I got it from, so "Thanks!" to whoever it was that posted the original code somewhere out there.
Sub Macro1
Sheets("Sheet1").Select
MsgBox "The last row found is: " & Last(1, ActiveSheet.Cells)
MsgBox "The last column (R1C1) found is: " & Last(2, ActiveSheet.Cells)
MsgBox "The last cell found is: " & Last(3, ActiveSheet.Cells)
MsgBox "The last column (A1) found is: " & Last(4, ActiveSheet.Cells)
End Sub
Function Last(choice As Integer, rng As Range)
' 1 = last row
' 2 = last column (R1C1)
' 3 = last cell
' 4 = last column (A1)
Dim lrw As Long
Dim lcol As Integer
Select Case choice
Case 1:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Case 2:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Case 3:
On Error Resume Next
lrw = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
lcol = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Last = Cells(lrw, lcol).Address(False, False)
If Err.Number > 0 Then
Last = rng.Cells(1).Address(False, False)
Err.Clear
End If
On Error GoTo 0
Case 4:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Last = R1C1converter("R1C" & Last, 1)
For i = 1 To Len(Last)
s = Mid(Last, i, 1)
If Not s Like "#" Then s1 = s1 & s
Next i
Last = s1
End Select
End Function
Function R1C1converter(Address As String, Optional R1C1_output As Integer, Optional RefCell As Range) As String
'Converts input address to either A1 or R1C1 style reference relative to RefCell
'If R1C1_output is xlR1C1, then result is R1C1 style reference.
'If R1C1_output is xlA1 (or missing), then return A1 style reference.
'If RefCell is missing, then the address is relative to the active cell
'If there is an error in conversion, the function returns the input Address string
Dim x As Variant
If RefCell Is Nothing Then Set RefCell = ActiveCell
If R1C1_output = xlR1C1 Then
x = Application.ConvertFormula(Address, xlA1, xlR1C1, , RefCell) 'Convert A1 to R1C1
Else
x = Application.ConvertFormula(Address, xlR1C1, xlA1, , RefCell) 'Convert R1C1 to A1
End If
If IsError(x) Then
R1C1converter = Address
Else
'If input address is A1 reference and A1 is requested output, then Application.ConvertFormula
'surrounds the address in single quotes.
If Right(x, 1) = "'" Then
R1C1converter = Mid(x, 2, Len(x) - 2)
Else
x = Application.Substitute(x, "$", "")
R1C1converter = x
End If
End If
End Function
I would like to add one more reliable way using UsedRange to find the last used row:
lastRow = Sheet1.UsedRange.Row + Sheet1.UsedRange.Rows.Count - 1
Similarly to find the last used column you can see this
Result in Immediate Window:
?Sheet1.UsedRange.Row+Sheet1.UsedRange.Rows.Count-1
21
Public Function GetLastRow(ByVal SheetName As String) As Integer
Dim sht As Worksheet
Dim FirstUsedRow As Integer 'the first row of UsedRange
Dim UsedRows As Integer ' number of rows used
Set sht = Sheets(SheetName)
''UsedRange.Rows.Count for the empty sheet is 1
UsedRows = sht.UsedRange.Rows.Count
FirstUsedRow = sht.UsedRange.Row
GetLastRow = FirstUsedRow + UsedRows - 1
Set sht = Nothing
End Function
sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used
if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.
This function calculate the first row number of UsedRange plus number of UsedRange rows.
Last_Row = Range("A1").End(xlDown).Row
Just to verify, let's say you want to print the row number of the last row with the data in cell C1.
Range("C1").Select
Last_Row = Range("A1").End(xlDown).Row
ActiveCell.FormulaR1C1 = Last_Row
get last non-empty row using binary search
returns correct value event though there are hidden values
may returns incorrect value if there are empty cells before last non-empty cells (e.g. row 5 is empty, but row 10 is last non-empty row)
Function getLastRow(col As String, ws As Worksheet) As Long
Dim lastNonEmptyRow As Long
lastNonEmptyRow = 1
Dim lastEmptyRow As Long
lastEmptyRow = ws.Rows.Count + 1
Dim nextTestedRow As Long
Do While (lastEmptyRow - lastNonEmptyRow > 1)
nextTestedRow = Application.WorksheetFunction.Ceiling _
(lastNonEmptyRow + (lastEmptyRow - lastNonEmptyRow) / 2, 1)
If (IsEmpty(ws.Range(col & nextTestedRow))) Then
lastEmptyRow = nextTestedRow
Else
lastNonEmptyRow = nextTestedRow
End If
Loop
getLastRow = lastNonEmptyRow
End Function
Function LastRow(rng As Range) As Long
Dim iRowN As Long
Dim iRowI As Long
Dim iColN As Integer
Dim iColI As Integer
iRowN = 0
iColN = rng.Columns.count
For iColI = 1 To iColN
iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row
If iRowI > iRowN Then iRowN = iRowI
Next
LastRow = iRowN
End Function
Sub test()
MsgBox Worksheets("sheet_name").Range("A65536").End(xlUp).Row
End Sub
This is looking for a value in column A because of "A65536".
The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.
Selection.End(xlDown).Select
MsgBox(ActiveCell.Row)

How to find the true Last Cell in any Worksheet

This question is now answered elegantly, thanks to Chris Neilsen, see the answer below. It is the one I will use from now on. The solution reliably finds the last cell in a Worksheet, even when cells are hidden by Filters, Groups or Local hiding of rows.
The discussion may be informative to some, so I have provided an optimised version of my own code too. It demonstrates how to save and restore Filters, uses #Chis's ideas for finding the last Row, and records Hidden Row Ranges in a short Variant array from which they are finally restored.
A test Workbook that explores and tests all the solutions proposed discussed is also available to download here.
THE FULL QUESTION AND DISCUSSION, AS UPDATED
There is much discussion here and elsewhere on finding last cells in Excel Worksheets. The Range.SpecialCells method has limitations and does not always find the true last cell. This is particularly true if Worksheet.AutoFilters are active. The code below solves the problem and returns the correct result, even if Filters are active, cells are Grouped and Hidden, or Rows or Columns are Hidden using Hide/Unhide. However, the method is not simple. Does anybody know of a better method that is consistently reliable?
The 'true last cell' is understood to be the intersection of the last row containing data or formulae and the last column containing them. Formatting may extend past it.
Credits and thanks for good ideas: to readify and sancho s.
The code below tests and works in my application in Excel 2010 and requires that Scripting.Runtime is referenced in the VBIDE. It contains inline comments that document what it is doing and why. Also, the variable names are deliberately explanatory. Sorry, but this makes them long.
In some circumstances it may not restore the exact Rows that were hidden when it is called. I have never had this happen.
Edit 1 to the question
Thanks to the 3 kind respondees on 1/3/2016.
This follows on from brettdj marking the question as already answered. Regrettably, I do not believe that to be true. At least, not unless UsedRange can be trusted in all circumstances. Though problems with SpecialCells are hard to reproduce, previous experience with the values provided by SpecialCells discourages reliance on them.
brettdj's post Return a range from A1 to the true last used cell provides a solution, GetRange. It is one amongst others but appears to be clearly the best. I have tested it and all the solutions proposed in this thread. In my tests, none of them are able to find the last cell when a filter is active without trusting UsedRange. brettdj, of high reputation, clearly thinks otherwise but it appears to me that I really have detected a real issue.
To demonstrate:
See the following test Sheet. All rows and columns are exposed in this view. Note Row 19 with the text 'Row to hide with filter' in H19. Also note that there is information in Row 20 at B20 and in Column J at J11. (Obviously, as this is a test, there is nothing in J20 the Cell whose reference is the correct answer to the Question):
Tests were run on the Sheet above but with a filter active (emphasised by a red circle in the image below) which removes row 19 from view. During the tests the Column Group J:K was collapsed but the Row Group over 19:20 was left visible.
These are the results (the true answer is J20):
Gettrange() by brettdj in the referenced Answer gives
"Range is A1:B20."
TrueLastCell() by Gary's Student gives "The
TRUE last cell is B20" and also may sometimes be very expensive, looping from very high row and column numbers if the UsedRange goes to the end of a largely empty Sheet. (Also, the screen shot in the answer shows C11 when it should be F11.)
GetTrueLastCell(WS) by PatrickK gets the right answer, J20 but
it relies entirely on UsedRange which I understand is not possible,
or I would never have started on this!
GetTrueLastCell(WS,,) (by me, the code below, though complicated) gives $J$20.
In the unlikely case that this is Operating System specific, my test was run on {you're not allowed to laugh -:)} Vista Home Premium. My excuse is that it is 64Bit OS on a lightning fast 8 core machine, even if it is ageing.
Excel 2010, 32 bit Version 14.0.7166.5000.
Edit 2 in response
In response to chris neilsen's request for validation and a test file upload it is no longer here. The short answer is : The problem is all too reproducible on Windows 10 running Office 2013 15.0.4797.1003 as well as on Vista - Office 2010. Sadly, this is real. The Workbook from which the images were taken now contains the code for each the suggestions made here (to date 2 March 2016). The public file downloads OK and reproduces the results on a Windows 7/Office 2010 machine. To run the tests, look for the Module TestSolutionsProposed in the VBIDE. The Debug.Prints from the tests give identical same results on W10, W7, Vista and Office 2010 & 2013 (correct answer is J20):
Brettdj's GetRange gives: Range is A1:B20
WS usedrange = $A$1:$K$20
PatrickK's GetTrueLastCell gives Found last cell = $K$20
Gary's Student's TrueLastCell gives: The TRUE last cell is B20
My GetTrueLastCell (with RemoveFiltersAsBoolean = False) gives: Last cell address is B20
My GetTrueLastCell (with RemoveFiltersAsBoolean = True) gives: Last cell address is J20
#brettdj - please can you restore the status of this question? Surely it is reproducible by others - how could the results be specific to three separate systems I can get access to but not to others? Only removal of the filters gives the correct answer. Note: The filter has to be both present and active to show the problem; as uploaded, the Test Workbook is set to give the results above; it is not enough to have AutoFitlerMode = True. One of the filters must have a filter criterion active - in the example H19 is hidden.
Private Function GetTrueLastCell(ws As Excel.Worksheet, _
Optional lRealLastRow As Long, _
Optional lRealLastColumn As Long, _
Optional RemoveFiltersAsBoolean As Variant = False) As Range
'Purpose:
'Finds the cell at the intersection of the last Row containing any data and the last Column containing any data,
' even if some cells are hidden by Filters, Grouping or are locally Hidden. If there are no filters uses a simple method.
'Returns: the LastCell as a Range; Optionally returns Row and Column indeces.
' If the WS has no data or is not a WS, returns GetTrueLastCell=Nothing & lRealLastRow=0 & RealLastColumn=0
'Developed by extension of ideas from:
' 'Readify' for ideas about saving and restoring filters,
' see: https://stackoverflow.com/questions/9489126/in-excel-vba-how-do-i-save-restore-a-user-defined-filter
' 'Sancho s' 24/12/2014, see https://stackoverflow.com/questions/24612874/finding-the-last-cell-in-an-excel-sheet
'Written by Neil Dunlop 29/2/2016
'History: 2016 03 03 added optimisation of the reapplication of filters following discussion on StackOverFlow wiht
' thanks to Chris Neilsen for review and comments and ideas - see here:
' https://stackoverflow.com/questions/35712424/how-to-find-the-true-last-cell-in-any-worksheet
'Notes:
'This will find the last cell even if rows are Hidden by any means.
' This is partly accomplished by setting Lookin:=xlFormulas,
' and partly by removing and restoring filters that prevent .Find looking in a cell.
'Requirements:
' The reference to Microsoft Scripting Runtime must be present in the VBIDE's Tools>References list.
Dim FilteredRange As Range, rng As Range
Dim wf As Excel.WorksheetFunction
Dim MyCriteria1 As Scripting.Dictionary
Dim lr As Long, lr2 As Long, lr3 As Long
Dim i As Long, j As Long, NumFilters As Long
Dim CurrentScreenStatus As Boolean, LastRowHidden As Boolean
Dim FilterStore() As Variant, OutlineHiddenRow() As Variant
If Not RemoveFiltersAsBoolean Then GoTo JUSTSEARCH
CurrentScreenStatus = Excel.Application.ScreenUpdating
Excel.Application.ScreenUpdating = False
On Error GoTo BADWS
If ws.AutoFilterMode Then
'Save all active Filters
With ws.AutoFilter
If .Filters.Count > 0 Then
Set FilteredRange = .Range
For i = 1 To .Filters.Count
If .Filters(i).On Then
NumFilters = NumFilters + 1
ReDim Preserve FilterStore(0 To 4, 1 To NumFilters)
FilterStore(0, NumFilters) = i 'The Column to which the filter applies
'If there are only 2 Filters they will be in Criteria1 and Criteria2.
'Above 2 Filters, Criteria1 contains all the filters in a Scripting Dictionary
FilterStore(1, NumFilters) = .Filters(i).Count 'The number of conditions active within this filter
Select Case .Filters(i).Count
Case Is = 1 'There is 1 filter in Criteria1
FilterStore(2, NumFilters) = .Filters(i).Criteria1
Case Is = 2 'There are 2 Filters in Criteria1 and Criteria2
FilterStore(2, NumFilters) = .Filters(i).Criteria1
FilterStore(3, NumFilters) = .Filters(i).Criteria2
Case Else 'There are many filters, they need to be in a Scripting Dictionary in Criteria1
Set MyCriteria1 = CreateObject("Scripting.Dictionary")
MyCriteria1.CompareMode = vbTextCompare
For j = 1 To .Filters(i).Count
MyCriteria1.Add Key:=CStr(j), Item:=.Filters(i).Criteria1(j)
Next j
Set FilterStore(2, NumFilters) = MyCriteria1
End Select
If .Filters(i).Operator Then
FilterStore(4, NumFilters) = .Filters(i).Operator
End If
End If
Next i
End If ' .Filters.Count > 0
End With
'Check for and store any hidden Outline levels applied to the Rows.
'At this stage the last cell is not known, so the best available estimate , UsedRange,
' is used in the Row loop. The true maximum row number with data may be less than the
' highest row from UsedRange. The code below reduces the maximum estimated efficiently.
'It is believed that UsedRange is never too small; it it were, then the hidden properties
' of some rows may not be stored and will therefore not be restored later.
'---------get a true last row---------------------------------------------------------
Set rng = ws.Range(ws.Cells(1, 1), ws.UsedRange.Cells(ws.UsedRange.Cells.CountLarge))
Set wf = Application.WorksheetFunction
With rng 'Code from Chris Neilsen
lr = .Rows.Count + .Row - 1
lr2 = lr \ 2
lr3 = lr2 \ 2
Do While (lr - lr2) > 30
'Debug.Print "r", lr2, lr
If wf.CountA(.Rows(lr2 & ":" & lr)) = 0 Then
lr = lr2
lr2 = lr3
lr3 = lr2 \ 2
Else
lr3 = lr2
lr2 = (lr + lr2) \ 2
End If
Loop
For i = lr To 1 Step -1
If wf.CountA(.Rows(i)) <> 0 Then Exit For
Next i
lr = i
End With ' rng
'---------record and unhide any hidden Row--------------------------------------------
j = 0
LastRowHidden = False
For i = 1 To lr
If (Not ws.Rows(i).Hidden And LastRowHidden) Then
'End of a Hidden Rows Range, record the Range
Set OutlineHiddenRow(2, j) = ws.Rows(OutlineHiddenRow(1, j) & ":" & i - 1)
LastRowHidden = False
ElseIf ws.Rows(i).Hidden And Not LastRowHidden Then 'Start of Hidden Rows Range, record the Row
j = j + 1
ReDim Preserve OutlineHiddenRow(1 To 2, 1 To j) ' 1 -first row found to be Hidden, 2 - Range of Hidden Rows(i:j)
If i <> lr Then
OutlineHiddenRow(1, j) = i
LastRowHidden = True
Else 'Last line in range is hidden all on its own
Set OutlineHiddenRow(2, j) = ws.Rows(i & ":" & i)
End If
ElseIf LastRowHidden And ws.Rows(i).Hidden And i = lr Then 'Special case is for Hidden Range ending on last Row
Set OutlineHiddenRow(2, j) = ws.Rows(OutlineHiddenRow(1, j) & ":" & i)
Else
'Nothing to do
End If
Next i
NumFilters = j
'Remove the AutoFilter, if any of the filters were On.
' This changes the hidden setting for ALL Rows (but NOT Columns) to visible
' irrespective of the reason for their having become hidden (Filter, Group, local Hide).
If NumFilters > 0 Then ws.AutoFilterMode = False
End If ' WS.AutoFilterMode
JUSTSEARCH:
'Search for the last cell that contains any sort of 'formula'.
'xlPrevious ensures that the search starts from the end of the last Row or Column (it's the next cell after (1,1)).
'LookIn:=xlFormulas ensures that the search includes a search across Hidden data.
' However, if ANY filters are active the search NO LONGER LOOKS IN HIDDEN CELLS. Also the reverse search
' starts at the end of the column or row containing (1,1) instead of starting at the very end row and column.
' This is why all filters have to be stored, removed and reapplied to find the correct end cell.
lRealLastColumn = ws.Cells.Find(What:="*", _
After:=ws.Cells(1, 1), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False, _
MatchByte:=False, _
SearchFormat:=False).Column
If lr = 0 Then
lRealLastRow = ws.Cells.Find(What:="*", _
After:=ws.Cells(1, 1), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False, _
MatchByte:=False, _
SearchFormat:=False).Row
Else
lRealLastRow = lr
End If
Set GetTrueLastCell = ws.Cells(lRealLastRow, lRealLastColumn)
'Restore the saved Filters to their Rows.
If NumFilters Then
'Restore the original AutoFilter settings
FilteredRange.AutoFilter
With ws.AutoFilter
For i = 1 To UBound(FilterStore, 2)
If FilterStore(4, i) Then 'There is an Operator
If FilterStore(1, i) > 2 Then 'There is a ScriptingDictionary for Criteria1
FilteredRange.AutoFilter Field:=FilterStore(0, i), _
Criteria1:=FilterStore(2, i).Items, _
Criteria2:=FilterStore(3, i), _
Operator:=FilterStore(4, i)
Else 'Criteria 1 is a string
FilteredRange.AutoFilter Field:=FilterStore(0, i), _
Criteria1:=FilterStore(2, i), _
Criteria2:=FilterStore(3, i), _
Operator:=FilterStore(4, i)
End If
Else 'No Operator
If FilterStore(1, i) > 2 Then 'There is a ScriptingDictionary for Criteria1
FilteredRange.AutoFilter Field:=FilterStore(0, i), _
Criteria1:=FilterStore(2, i).Items
Else 'Criteria 1 is a string
FilteredRange.AutoFilter Field:=FilterStore(0, i), _
Criteria1:=FilterStore(2, i)
End If
End If
Next i
End With
End If ' NumFilters
If NumFilters > 0 Then
'Restore the Hidden status of any Rows that were revealed by setting WS.AutoFilterMode = False.
'Rows, not columns are filtered. Columns' Hidden status does not need to be restored
' because AutoFilter does not unhide Columns.
For i = 1 To NumFilters
OutlineHiddenRow(2, i).Hidden = True 'Restore the hidden property to the stored Row Range
Next i
End If ' NumFilters > 0
GoTo ENDFUNCTION
BADWS:
lRealLastRow = 0
lRealLastColumn = 0
Set GetTrueLastCell = Nothing
ENDFUNCTION:
Set wf = Nothing
Set MyCriteria1 = Nothing
Set FilteredRange = Nothing
Excel.Application.ScreenUpdating = CurrentScreenStatus
End Function
Based on #Gary's method, but optimised to work fast when the UsedRange is Large but not reflective of the True Last Cell (as can happen when a cell on the extreames of a worksheet is inadvertently formatted)
It works by, starting with the UsedRange, counting cells in half the range and halving the referenced test range above or below the split point depending on the count result, and repeating until it reaches < 5 rows/columns, then uses a linear search from there.
Function TrueLastCell( _
ws As Excel.Worksheet, _
Optional lRealLastRow As Long, _
Optional lRealLastColumn As Long _
) As Range
Dim lrTo As Long, lcTo As Long, i As Long
Dim lrFrom As Long, lcFrom As Long
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction
With ws.UsedRange
lrTo = .Rows.Count
lcTo = .Columns.Count
lrFrom = lrTo \ 2
Do While (lrTo - lrFrom) > 2
If wf.CountA(.Rows(lrFrom & ":" & lrTo)) = 0 Then
lrTo = lrFrom - 1
lrFrom = lrFrom \ 2
Else
lrFrom = (lrTo + lrFrom) \ 2
End If
Loop
If wf.CountA(.Rows(lrFrom & ":" & lrTo)) = 0 Then
lrTo = lrFrom - 1
Else
For i = lrTo To lrFrom Step -1
If wf.CountA(.Rows(i)) <> 0 Then
Exit For
End If
Next i
lrTo = i
End If
lcFrom = lcTo \ 2
Do While (lcTo - lcFrom) > 2
If wf.CountA(Range(.Columns(lcFrom), .Columns(lcTo))) = 0 Then
lcTo = lcFrom - 1
lcFrom = lcFrom \ 2
Else
lcFrom = (lcTo + lcFrom) \ 2
End If
Loop
If wf.CountA(Range(.Columns(lcFrom), .Columns(lcTo))) = 0 Then
lcTo = lcFrom - 1
Else
For i = lcTo To 1 Step -1
If wf.CountA(.Columns(i)) <> 0 Then
Exit For
End If
Next i
lcTo = i
End If
Set TrueLastCell = .Cells(lrTo, lcTo)
lRealLastRow = lrTo + .Row - 1
lRealLastColumn = lcTo + .Column - 1
End With
End Function
On my hardware it runs in about 2ms on a sheet with UsedRange extending to the sheet limits and True Last Cell at F5, and 0.1ms when UsedRange reflects the True Last Cell at F5
Edit: slightly more optimised search
UsedRange may be erroneous, (it may be too large), but we can start with its outer limits and work inwards:
Sub TrueLastCell()
Dim lr As Long, lc As Long, i As Long
Dim wf As WorksheetFunction
Set wf = Application.WorksheetFunction
ActiveSheet.UsedRange
With ActiveSheet.UsedRange
lr = .Rows.Count + .Row - 1
lc = .Columns.Count + .Column - 1
End With
For i = lr To 1 Step -1
If wf.CountA(Rows(i)) <> 0 Then
Exit For
End If
Next i
For i = lc To 1 Step -1
If wf.CountA(Cells(lr, i)) <> 0 Then
MsgBox "The TRUE last cell is " & Cells(lr, i).Address(0, 0)
Exit Sub
End If
Next i
End Sub
Great question.
As you note, Find failes with AutoFilter. As an alternative to looping through the filters, or the range loop used by another answer you could
Copy the sheet and remove the AutoFilter
use xlformulas in the Find routine which caters to hidden cells
So something lke this:
Sub GetRange()
'by Brettdj, http://stackoverflow.com/questions/8283797/return-a-range-from-a1-to-the-true-last-used-cell
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim ws As Worksheet
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
ActiveSheet.Copy
Set ws = ActiveSheet
With ws
.AutoFilterMode = False
Set rng1 = ws.Cells.Find("*", ws.[a1], xlFormulas, , xlByRows, xlPrevious)
Set rng2 = ws.Cells.Find("*", ws.[a1], xlFormulas, xlPart, xlByColumns, xlPrevious)
If Not rng1 Is Nothing Then
Set rng3 = Range([a1], Cells(rng1.Row, rng2.Column))
MsgBox "Range is " & rng3.Address(0, 0)
Debug.Print "Brettdj's GetRange gives: Range is " & rng3.Address(0, 0) 'added for this test by ND
'if you need to actual select the range (which is rare in VBA)
Application.GoTo rng3
Else
MsgBox "sheet is blank", vbCritical
End If
.Parent.Close False
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
I think you can utilize the .UsedRange property from the Worksheet object. Try below:
Option Explicit
Function GetTrueLastCell(WS As Worksheet) As Range
With WS
If .UsedRange.Count = 1 Then
Set GetTrueLastCell = .UsedRange
Else
Set GetTrueLastCell = .Range(Split(.UsedRange.Address, ":")(1))
End If
End With
End Function
Best way I know to find "true Last Cell" is to use 2 steps:
Pick last cell of UsedRange (i.e. UsedRange.Cells.CountLarge)
Move left & up until you find last non-empty row & column with CountA (i.e. WorksheetFunction.CountA(Range)), as it is fast, and works with Hidden / AutoFiltered / Grouped ranges.
This takes some time, so I've written an optimized code for the second step.
Then I found #Chris' code edited on Nov 30, 2019, and it looked similar, though I was wondering why so different. I compared (...did my best to do apple v apple), and was surprised by the results.
If my tests are reliable, then all what matters is how many searches you do with CountA. I call it cycle - it is actually the number of CountA functions!
My routine does up to 34 cycles, and #Chris' routine seems to do up to 32..80+ cycles. His code seems to test the same ranges repeatedly.
Please have a look at the test table Link, see my test results in VBA notes, and watch Immediate for your live results. You may test with any content, or even use an ActiveSheet in your own WorkBook. Play with parameters in VBA at "==== PARAMETERS TO BE CHANGED ====". You may zoom to 10%-15% to see painted cells showing the search ranges for each cycle. That's where the number of cycles becomes visible.
Note: I have not found any side-effects or errors with this so far. I avoid using Range.Find, and changing its parameters behind the scenes. Some users will learn it the hard way... - like I did, when I then replaced text in the entire workbook, just to find it out days later.
Note2: This is my first post, please excuse possible glitches here.
Function GetLastSheetCellRng(ws As Excel.Worksheet) As Range
'Returns the [Range] of last used cell of the specified [Worksheet], located in the cross-section of the bottom row and right column with non-empty cells
Dim wf As Excel.WorksheetFunction: Set wf = Application.WorksheetFunction
Dim Xfound&, Yfound&, Xfirst&, Yfirst&, Xfrom&, Yfrom&, Xto&, Yto As Long
With ws
'1. step: UsedRange last cell
Set GetLastSheetCellRng = .UsedRange.Cells(.UsedRange.Cells.CountLarge) 'Getting UsedRange last cell
Yfound = GetLastSheetCellRng.Row: Xfound = GetLastSheetCellRng.Column
'2. step: Check non-empty cells in UsedRange last cell row & column
'If not found, then search up for last non-empty row, and search left for last non-empty column
If (wf.CountA(.Rows(Yfound)) = 0) And (Yfound > 1) Then
Yto = Yfound
Yfrom = Yto \ 2
Yfirst = 0
Do
If wf.CountA(.Range(.Rows(Yfrom), .Rows(Yto))) <> 0 Then
Yfirst = Yfrom
Yfrom = (Yfirst + Yto + 0.5) \ 2
Else
Yto = Yfrom - 1
Yfrom = (Yfrom + Yfirst) \ 2
End If
Loop Until Yfirst = Yfrom
If Yfirst = 0 Then
Yfound = 1 'If no cell found, then 1st row returned
Else
Yfound = Yfirst
End If
End If
If (wf.CountA(.Columns(Xfound)) = 0) And (Xfound > 1) Then
Xto = Xfound
Xfrom = Xto \ 2
Xfirst = 0
Do
If wf.CountA(.Range(.Columns(Xfrom), .Columns(Xto))) <> 0 Then
Xfirst = Xfrom
Xfrom = (Xfirst + Xto + 0.5) \ 2
Else
Xto = Xfrom - 1
Xfrom = (Xfrom + Xfirst) \ 2
End If
Loop Until Xfirst = Xfrom
If Xfirst = 0 Then
Xfound = 1 'If no cell found, then 1st column returned
Else
Xfound = Xfirst
End If
End If
Set GetLastSheetCellRng = .Cells(Yfound, Xfound)
End With
End Function

Search for two values and copy everything in between in a loop

I have a worksheet which has many terms in Column A.I want to search for two terms for example
term A and term B and copy all rows between the two terms and paste it into a new sheet.These two terms may repeat in the column. The problem which I am basically facing the following problem : whenever I run my code it also copies rows between term B and term A which is unnecessary. Following is the code i am using for two terms term A and term B.
For example my column A is
Institute
Event
Job
Computer
Laptop
Figures
Event
figures
format
computer
and many more terms
I want to copy all the rows between term A: Event and term B: Laptop and paste it into a new sheet. What my code is doing is it is copying the rows between all combinations of Event and computer. Even the rows between computer and event are copied(in this case Figure and laptop).
Sub OpenHTMLpage_SearchIt()
Dim Cell As Range, Keyword$, N%, SearchAgain As VbMsgBoxResult
Dim ass As Variant
Dim Cellev As Range, prakash$, P%, SearchAgaina As VbMsgBoxResult
Dim asa As Variant
StartSearch:
N = 1
Keyword = "Event"
If Keyword = Empty Then GoTo StartSearch
For Each Cell In Range("A1:A500")
If Cell Like "*" & Keyword & "*" Then
ass = Cell.Address
P = 1
prakash = "Computer"
If prakash = Empty Then GoTo StartSearch
For Each Cellev In Range("A1:A500")
If Cellev Like "*" & prakash & "*" Then
asa = Cellev.Address
Range(asa, ass).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Range("B13").Select
ActiveSheet.Paste
Worksheets("sheet1").Select
P = P + 1
End If
Next Cellev
N = N + 1
End If
Next Cell
End Sub
Edit: code formatting.
The following is the code which is working for me.This copies everything in between Event and laptop and pastes it into a new sheet. Then again it searches for a second time and this time the search will start from the next row to the first search.I hope I am clear with this.
Sub Star123()
Dim rownum As Long
Dim colnum As Long
Dim startrow As Long
Dim endrow As Long
Dim lastrow As Long
rownum = 1
colnum = 1
lastrow = Worksheets("Startsheet").Range("A65536").End(xlUp).Row
With ActiveWorkbook.Worksheets("StartSheet").Range("a1:a" & lastrow)
For rownum = 1 To lastrow
Do
If .Cells(rownum, 1).Value = "Event" Then
startrow = rownum
End If
rownum = rownum + 1
If (rownum > lastrow) Then Exit For
Loop Until .Cells(rownum, 1).Value = "Laptop"
endrow = rownum
rownum = rownum + 1
Worksheets("StartSheet").Range(startrow & ":" & endrow).Copy
Sheets("Result").Select
Range("A1").Select
ActiveSheet.Paste
Next rownum
End With
End Sub
Try this:
Sub DoEeeeeet(sheetName, termA, termB)
Dim foundA As Range, _
foundB As Range
Dim newSht As Worksheet
With Sheets(sheetName).Columns(1)
Set foundA = .Find(termA)
If Not foundA Is Nothing Then
Set foundB = .Find(termB, after:=foundA, searchdirection:=xlPrevious)
End If
End With
If foundA Is Nothing Or foundB Is Nothing Then
MsgBox "Couldn't find " & IIf(foundA Is Nothing, termA, termB)
Else
Range(foundA, foundB).Copy
Set newSht = Sheets.Add
newSht.Range("B13").PasteSpecial
End If
End Sub
You can call it as follows:
DoEeeeeet "Sheet1","Event","Laptop"
It'll find the first instance of "Event" and the last instance of "Laptop" on the sheet named "Sheet1" and copy all of that data to B13 and subsequent cells in a new sheet.
Is that what you want? Or do you want each of the subranges beginning with "Event" and ending with "Laptop"?