VBA - Set Range Between Two Dates Using Search Function - vba

I'm trying to get my VBA code to search through a column for a user-inputted value (on a form) and set a range based on the values.
I need the code to scan DOWN through the column until it finds the value (which is a date) and then scan UP through the column to get the second part of the range. I need it to be like this because there might be multiple instances of the same date and they all need to be accounted for.
I've tried this:
StartRange = ws.Cells.Find(What:=StartDate, SearchOrder:=xlRows, _
SearchDirection:=xlNext, LookIn:=xlValues)
EndRange = ws.Cells.Find(What:=EndDate, SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues)
But it's not working the way I had expected and is erroring. (Edit: the WS has been defined, so I know that's not the issue). I don't even know if I'm going about this the right way
I'm feeling defeated :(
Any help would be appreciated, Thanks in advance!
Edit:
I've yet to try any of the suggestions as I am away from my project at the moment, but I feel I need to clarify a few things.
The dates will always be in chronological order, I have a script that organises them on sheet activation
I need to be able to error handle dates that do not appear in the database, I also need the script to be able to "skip over" dates that don't exist. Ie, 1st 1st 1st, 3rd, 3rd, 5th. If my start and end dates were the 1st and 5th, the entire example would be the range.
Thanks for your help so far guys though, I appreciate it!
EDIT2:
I've tried a few answers and have added this in to my code, but it is now failing on a Range_Global fail.
Dim startrange, endrange, searchrange As Range
LookUpColumn = 2
With ws.Columns(LookUpColumn)
Set startrange = .Find(What:=Me.R_Start.Value, _
After:=ws.Cells(.Rows.count, LookUpColumn), _
SearchOrder:=xlRows, _
SearchDirection:=xlNext, LookIn:=xlValues)
Set endrange = .Find(What:=Me.R_End.Value, _
After:=ws.Cells(5, LookUpColumn), _
SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues)
searchrange = Range(startrange, endrange)
MsgBox searchrange.Address
End With
Any suggestions?

Using Find is the right way to do this type of thing, you just need to get a few details right.
Use Set to assign range references. Eg Set StartRange = ... (and make sure to Dim StartRange as Range). Ditto EndRange and SearchRange
Specify a After cell. Note that by default this is the Top Left cell of the search range, and the search begins after this cell. If your StartDate happens to be in cell A1 (and another cell) then leaving as default will return the wrong result
Limit the search range to the column of interest.
Dim all your variables. Each variaqble needs its own As (and use Option Explicit)
End result
Dim startrange As Range, endrange As Range, searchrange As Range
Dim LookUpColumn as Long
LookUpColumn = 2
With ws.Columns(LookupColumn)
' Make sure lookup column data is type Date
Set searchrange = .SpecialCells(xlCellTypeConstants)
searchrange.Value = searchrange .Value
Set searchrange = Nothing
Set StartRange = .Find(What:=CDate(StartDate), _
After:=.Cells(.Rows.Count, LookupColumn), _
SearchOrder:=xlRows, _
SearchDirection:=xlNext, LookIn:=xlValues)
Set EndRange = .Find(What:=CDate(EndDate), _
After:=.Cells(1, LookupColumn), _
SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues)
End With
Set searchrange = Range(startrange, endrange)
MsgBox searchrange.Address

Let's start with this and see what needs to be fine tuned.
This code will look for a date (based on input) and find the position of that date in a column. Same with the "EndDate" and then creates a range on that column between the 2 positions.
Sub ARange()
Dim Sh As Worksheet: Set Sh = Sheets("Sheet1")
Dim i, j As Integer
LookupColumn = "A" 'Define the LookupColum / If you find using column index to be simpler then you need to switch the search from (range) to (cells)
StartDate_Value = Sh.Range("B2").Value 'Use whatever you need to define the input values
EndDate_Value = Sh.Range("C2").Value 'Use whatever you need to define the input values
For i = 1 To 30000
If Sh.Range(LookupColumn & i).Value = EndDate_Value Then EndDate_Row = i
Next i
For j = EndDate_Row To 1 Step -1
If Sh.Range(LookupColumn & j).Value = StartDate_Value Then StartDate_Row = j
Next j
Dim MyDateRange As Range: Set MyDateRange = Sh.Range(LookupColumn & StartDate_Row & ":" & LookupColumn & EndDate_Row)
MsgBox "MyDateRange = " & LookupColumn & StartDate_Row & ":" & LookupColumn & EndDate_Row
End Sub
Another approach should imply looking for the EndDate from bottom upwards (as in Excel's column values) and for the StartDate from top to bottom. like this:
For i = 30000 to 1 step -1
For j = 1 To 30000
And the 3rd (the charm):for the EndDate from top to bottom and for the StartDate from top to bottom. like this:
For i = 1 to 30000
For j = 1 To 30000
And the 4th (The One):
For i = 1 to 30000
For j = 30000 to 1 Step -1
On my home laptop the search on the 30.000 cells is instant (under 1s).
Give it a try and based on the feedback we can fine tune it.
On the Other hand, I might read your question as for looking To select not all values between the top / bottom position, but any cells with values of dates between the 2 input values neverminind the arrangement of the values within the list (column cells). i.e. If StartDate = 1.Jan.2013 and EndDate = 3.Jan.2013. The code should pick up 1,2 and 3 from the 30.000 list neverminind the position of these 3 dates (which in fact may be found thousands of times). If This is true, the solution may be simpler than the one above.

I don't like the concept of this date search for a couple of reasons..
It makes the assumption that the dates will always be in order
It makes the assumption that both the dates will exist in the list
Whilst these may be valid assumptions in this case, I'm sure there may be instances where this may not be the case...
I don't know the best way to do this but one alternative to consider is using the auto-filter
Something like:
Sub FindDateRange()
Dim sht As Worksheet
Dim column As Long
Set sht = Sheet1
Dim rng As Range, inclusiveRange As Range
Dim startDate As Long, endDate As Long
column = 2
On Error GoTo Err
startDate = DateValue("02/10/2012")
endDate = DateValue("05/10/2012")
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
sht.Cells(1, column).AutoFilter Field:=column, Criteria1:=">=" & startDate, Operator:=xlAnd _
, Criteria2:="<=" & endDate
Set rng = sht.Range(sht.Cells(2, column), sht.Cells(sht.Cells(sht.Rows.Count, column).End(xlUp).Row, column)).SpecialCells(xlCellTypeVisible)
sht.AutoFilterMode = False
If rng.Address = sht.Cells(1, column).Address Then
MsgBox Format(startDate, "dd-mmm-yyyy") & " - " & Format(endDate, "dd-mmm-yyyy") _
& vbCrLf & vbCrLf & "No instances of the date range exist"
Else
Set inclusiveRange = sht.Range(rng.Cells(1, 1), rng.Cells(rng.Count, 1))
MsgBox Format(startDate, "dd-mmm-yyyy") & " - " & Format(endDate, "dd-mmm-yyyy") _
& vbCrLf & vbCrLf & "the range is " & rng.Address & vbCrLf & vbCrLf & _
"inclusive range is " & inclusiveRange.Address
End If
continue:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
Err:
MsgBox Err.Description
GoTo continue
End Sub

Related

Converting Excel Formula to VBA Code With Dynamic Reference

I have in my code variable named MyCol that gets the number of the column by month that was selected in a userform. for example October is in column U and November is in column V. I have a formula that I recorded and the month that was chosen is part of it but it is a problem because RC format is with specific reference and my variable is an integer.
I want that the formula will be dynamic.
This is the formula (column U means month that was chosen):
=IFNA(IF(VLOOKUP(AA2,sheet1!F:F,1,0)=AA2,U2,0),0)
That is the relavant part of the code:
Dim MonthName As String
Dim myCol As Integer
MonthName = ListMonth.Value
With MainWB.Worksheets("sheet2")
.Activate
.Range("L1:W1").Find(MonthName, , xlValues, xlWhole).Activate
End With
ActiveCell.Select
myCol = Selection.Column
Range("AB2").Select
ActiveCell.FormulaR1C1 = _
"=IFNA(IF(VLOOKUP(RC[-1],sheet1!C[-22],1,0)=RC[-1],RC[" & myCol & "],0),0)"
Range("AB2").AutoFill Destination:=Range("AB2:AB" & MLR), Type:=xlFillDefault
Replace your :
Range("AB2").Select
ActiveCell.FormulaR1C1 = _
"=IFNA(IF(VLOOKUP(RC[-1],sheet1!C[-22],1,0)=RC[-1],RC[" & myCol & "],0),0)"
With:
Range("AB2").FormulaR1C1 = _
"=IFNA(IF(VLOOKUP(RC[-1],sheet1!C[-22],1,0)=RC[-1],RC[-" & Range("AB2").Column - myCol & "],0),0)"
However, if you want to make your code run faster, and also avoid all the unecessary Activate, ActiveCell, Select, try the code below:
Dim FindRng As Range
MonthName = ListMonth.Value
With MainWB.Worksheets("sheet2")
Set FindRng = .Range("L1:W1").Find(MonthName, , xlValues, xlWhole)
End With
If Not FindRng Is Nothing Then
myCol = FindRng.Column
Else ' find was not successful finding the month name
MsgBox "Unable to find " & MonthName, vbCritical
Exit Sub
End If
Range("AB2").FormulaR1C1 = _
"=IFNA(IF(VLOOKUP(RC[-1],sheet1!C[-22],1,0)=RC[-1],RC[-" & Range("AB2").Column - myCol & "],0),0)"

VBA: How to drag formulaS to the last used row?

Good day, please help me.
The scenario is like this, I have 7 different formulas assigned to 7 different top rows after the header. What I want to achieved is to drag this formulas down to the last used rows simultaneously. I successfully wrote a code on doing this but it is a static code, I want to do it in a dynamical way because every month the amount of data is different so my static code is not reliable.
Here is the code that I have wrote:
'format border
ActiveSheet.Range("BK1", "BQ22").Select
borderMeFn
Dim strFormulas_OR1_ASR_DATA_DETAILS(1 To 7) As Variant
strFormulas_OR1_ASR_DATA_DETAILS(1) = "=COUNTIF(LSR_WISOR_USERS_" & month & ".xlsx!$C:$C,J2)" 'WISOR_COUNT - counts the PON_VER in LSR_WISOR_USER file.
strFormulas_OR1_ASR_DATA_DETAILS(2) = "=IFERROR(VLOOKUP(J2,LSR_WISOR_USERS_" & month & ".xlsx!$C:$E,3,FALSE),"""")"
strFormulas_OR1_ASR_DATA_DETAILS(3) = "=IFERROR(VLOOKUP(H2,CPXLIST_" & month & ".xlsx!$A:$B,2,FALSE),"""")"
strFormulas_OR1_ASR_DATA_DETAILS(4) = "=IFERROR(VLOOKUP(H2, DDVRFY_" & month & ".xlsx!$A:$B,2,FALSE),"""")"
strFormulas_OR1_ASR_DATA_DETAILS(5) = "=IFERROR(VLOOKUP(H2,HTG_" & month & ".xlsx!$A:$D,4,FALSE),"""")"
strFormulas_OR1_ASR_DATA_DETAILS(6) = "=IFERROR(VLOOKUP(H2,RPON_" & month & ".xlsx!$A:$B,2,FALSE),"""")"
strFormulas_OR1_ASR_DATA_DETAILS(7) = "=IFERROR(VLOOKUP(H2,PROV_PLAN_" & month & ".xlsx!$A:$F,6,FALSE),"""")"
'apply formulas to designated cells
With ActiveWorkbook.Sheets("Sheet1")
.Range("BK2:BQ2").formula = strFormulas_OR1_ASR_DATA_DETAILS
End With
Worksheets("Sheet1").Range("BK2:BQ22").FillDown
'Range("BK2:BQ" & LastRow).FillDown
Thank you in advance.
Try the code below, explanations inside the code's comments:
Dim LastRow As Long, LastCell As Range
'apply formulas to designated cells
With ThisWorkbook.Worksheets("Sheet1")
.Range("BK2:BQ2").Formula = strFormulas_OR1_ASR_DATA_DETAILS
' use Find function to get last row
Set LastCell = .Cells.Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
If Not LastCell Is Nothing Then
LastRow = LastCell.Row
Else
MsgBox "Error!", vbCritical
End If
.Range("BK2:BQ" & LastRow).FillDown
End With

Copy rows to new sheet if date in a column range is between two dates decided by user

I am positively stuck!
I need to loop in column C of "Raw Data" Sheet till the last row and if the date value is between a starting date and an end date then copy that row to a new sheet "Week". Dates are defined by input box
inizio = InputBox("Data Inizio") 'start date
fine = InputBox("Data Fine") 'end date
Then
I store the last row of the "week" sheet with this formula borrowed from a google search (apology to the author but I cannot remember his/her name)
PriRigVuot = Worksheets("Week").Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
and then I run into problems while tring to copy the row that match the If statement
For Each cella In Range("c1:c50")
If Worksheets("Raw Data").Range(cella).Value >= inizio And Worksheets("Raw Data").Range(cella).Value <= fine Then
Worksheets("Raw Data").Range(cella).EntireRow.Copy _
Destination:=Worksheets("Week 34").Range("A" & PriRigVuot + 1)
Else
End If
Next Cella
I am aware that this code (if it worked at all) would copy the row in the same place over and over again but I am trying to tackle a step at a time
Thanks for any help in advance
First, you can store the last row used in sheet Week like this:
LastRow = ThisWorkbook.Sheets("Week").Range("A" & Rows.Count).End(xlUp).Row
In your For loop, you dont need to specify the whole object again, since the Range is already specified when you wrote the sentence. So, the code will be like this:
Dim sh As Worksheet
Dim LastRow As Long
Set sh = ThisWorkbook.Sheets("Raw Data")
LastRow = ThisWorkbook.Sheets("Week 34").Range("A" & Rows.Count).End(xlUp).Row
For Each cella In sh.Range("C1:C" & sh.Range("C" & Rows.Count).End(xlUp).Row) 'Dynamic range in column C
If cella >= inizio And cella <= fine Then
cella.EntireRow.Copy Destination:=Worksheets("Week 34").Range("A" & LastRow + 1)
End If
Next cella

Excel VBA macro for one column, if true, apply formula to another column

For context:
I would like for the program to look through column B, identify the first "< / >" (which is purely stylistic and can be changed if necessary - it's only used to break up the data) as the start of a week at cell B9 and the next "< / >" (end of the week) at B16. So the range I'm interested in is B10-B15. It would then sum those numbers from J10 to J15 (Earned column) and paste that sum in L16 (Week Total column). The same could then be done with 'Hours' and 'Week Hours'. For the following week (and thereafter) the 'end of the week' "< / >" becomes the start of the week, and the program continues until B200.
I don't have any experience with VBA and so made the following incomplete attempt (based on what I had found online) but felt too out of my depth not to ask for help.
Sub Work()
Dim rng As Range
Dim rngFound As Range
Set rng = Range("B:B")
Set rngFound = rng.Find("</>")
If rngFound Is "</>" Then
If Cell = "</>" Then
End If
End Sub
Thank you for any help and please let me know if I can be clearer or elaborate on something.
The following code will loop through 200 lines, looking for your symbol. When found, it will sum the numbers in column J for rows between the current row and the last symbol.
I've included two lines that will update the formula. To me, the 2nd one is easier to understand.
Sub Work()
Dim row As Integer
row = 4
Dim topRowToAdd As Integer 'Remember which row is the
'top of the next sum
topRowToAdd = 4
While row <= 200
If Cells(row, 2) = "</>" Then
'Cells(row, 10).FormulaR1C1 = "=SUM(R[" & -(row - topRowToAdd) & "]C[0]:R[" & -1 & "]C[0])"
Cells(row, 10).Value = "=SUM(J" & topRowToAdd & ":J" & row - 1 & ")"
topRowToAdd = row + 1
End If
row = row + 1
Wend
End Sub
Sub Work()
Dim rng As Range, rngFound As Range
Set rng = Range("B:B")
Set rngFound = rng.Find("</>")
If rngFound.Value2 = "</>" Then
'whatever you want to do
End If
End Sub
So at a second glance it looks like this. If you'd like to make it structured you'd need to use a countifs function first.
Sub Work()
Dim rng As Range, rngFound(1) As Range
Set rng = Range("B1:B200")
On Error GoTo Err 'it is quite possible it will run into an error if there are no matches and I'm too lazy for structured solution
Set rngFound(0) = rng.Find(What:="</>", LookAt:=xlWhole, SearchDirection:=xlNext) 'finds the first
Set rngFound(1) = rng.Find(What:="</>", LookAt:=xlWhole, SearchDirection:=xlNext, After:=rngFound(0)) 'finds the first after the first (i.e. the second)
Set rngFound(0) = rngFound(0).Offset(1, 8) '8 is the difference between B and J, row shifts as per description, I advise you to make it a variable
Set rngFound(1) = rngFound(1).Offset(-1, 8)
If rngFound(1).Row > rngFound(0).Row Then 'if it's not higher, then it recurred and found the first range again
rngFound(1).Offset(1, 2).Formula = "=SUM(" & Range(rngFound(0), rngFound(1)).Address & ")" 'L column will have the sum as a formula
Else
MsgBox "There is a single match in " & rng.Address(False, False)
End If
If False Then
Err:
MsgBox "There are no matches in " & rng.Address(False, False)
End If
End Sub
Now for the grand finale:
Sub Work()
Dim rng As Range, rngFound() As Range, rngdiff(1) As Long, rngcount As Long
Set rng = Range("B1:B200")
rngcount = rng.Cells.Count
ReDim rngFound(rngcount)
rngdiff(0) = Range("J1").Column - rng.Column ' the range that needs to be summed is in column J
rngdiff(1) = Range("L1").Column - rng.Column ' the range containing the formula is in column L
On Error GoTo Err 'it is quite possible it will run into an error if there are no matches and I'm too lazy for structured solution
Set rngFound(0) = rng.Find(What:="</>", LookAt:=xlWhole, SearchDirection:=xlNext) 'finds the first
'loop starts
For i = 1 To rngcount
Set rngFound(i) = rng.Find(What:="</>", LookAt:=xlWhole, SearchDirection:=xlNext, After:=rngFound(i - 1)) 'finds the next
If rngFound(i).Row > rngFound(i - 1).Row Then 'if it's not higher, then it recurred and found the first range again
rngFound(i).Offset(0, rngdiff(1)).Formula = "=SUM(" & Range(rngFound(i - 1).Offset(1, rngdiff(0)), rngFound(i).Offset(-1, rngdiff(0))).Address & ")" 'L column will have the sum as a formula
Else
Exit Sub 'if it recurred the deed is done
End If
Next i
If False Then
Err:
MsgBox "There are no matches in " & rng.Address(False, False)
End If
End Sub

Need to determine LastRow over the Whole Row

I am not a programmer but have managed to cobble together great amounts of code that work on 4 pretty large projects (Yay for me!) I have tried numerous ways to find the Last Row. Some work for me some don't. I can find a few that give me the "actual" last row regardless of blanks in Column A (this is what I need). Yet I CANNOT for my life figure how to integrate that code with the way I am passing values from my array from one workbook to another. All of the code works "As Is" but I need to find a better way of searching the whole row (currently columns A:O) for the Last Row and then copying the data over. Column A maybe empty at times and to avoid the code from being overwritten, that "Last Row" needs to check the whole row. I am currently forcing a hidden cell (A7) with a "." as a forced placeholder. Any advice would be awesome.
Option Explicit
Public Sub SaveToLog15()
Dim rng As Range, aCell As Range
Dim MyAr() As Variant
Dim n As Long, i As Long
Dim LastRow As Long
Dim NextCell As Range
Dim Sheet2 As Worksheet
Set Sheet2 = ActiveSheet
Application.ScreenUpdating = False
With Sheet2
' rng are the cells you want to read into the array.
' Cell A7 (".") is a needed "Forced Place Holder" for last row _
determination
' A7 will go away once "better" LastRow can be added to this code
Set rng = Worksheets("Main").Range("A7,D22,D19,D20,J22:J24,E23,D21,J25:J27,D62,D63,G51")
' counts number of cells in MyAr
n = rng.Cells.Count
' Redimensions array for above range
ReDim MyAr(1 To n)
' Sets start cell at 1 or "A"
n = 1
' Loops through cells to add data to the array
For Each aCell In rng.Cells
MyAr(n) = aCell.Value
n = n + 1
Next aCell
End With
On Error Resume Next
' Opens "Test Log.xls"
Workbooks.Open FileName:= _
"S:\Test Folder\Test Log.xls"
' SUBROUTINE 1 "Disable Sheet Protection and Show All" REMOVED
' Finds last row on Tab "Tracking" based on Column "A"
' Last row determination DOES NOT go to next row if first _
Column is blank
' Use A7 "." to always force Data to Col A
'**********************************************************************
'THIS WORKS FINE BUT DOES NOT RECOGNIZE THE POSSIBLE BLANK IN COL A.
With Worksheets("Incoming Data")
Set NextCell = Worksheets("Incoming Data").Cells _
(Worksheets("Incoming Data").Rows.Count, "A").End(xlUp).Offset(1, 0)
End With
' I need this code replaced by the following code or integrated into
' this code snippet. I am lost on how to make that happen.
'***********************************************************************
'***********************************************************************
'THIS CODE FINDS THE "ACTUAL" LAST ROW AND THIS IS WHAT I'D LIKE TO USE
' I need to figure how to integrate this code block with the above
' Or maybe redo the whole thing.
LastRow = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
MsgBox ("The Last Row Is: " & LastRow)
' I am not using this code in the program. It's just there to show
' what I need to use because it works. I need to make this code work
'WITH the above block.
'***********************************************************************
' Sets the size of the new array and copies MyAr to it
NextCell.Resize(1, UBound(MyAr)).Value = (MyAr)
' SUBROUTINE 2 "Add borders to cells in range" REMOVED
' SUBROUTINE 3 "Re-enable Sheet Protection" REMOVED
ActiveWorkbook.Save
'ActiveWindow.Close
Application.ScreenUpdating = True
MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
& "'Test Log.xls'", vbInformation, "Log Save Confirmation"
End Sub
This is a common problem with "jagged" data like:
Clearly here column B has that last row. Here is one way to get that overall Last row by looping over the four candidate columns:
Sub RealLast()
Dim m As Long
m = 0
For i = 1 To 4
candidate = Cells(Rows.Count, i).End(xlUp).Row
If candidate > m Then m = candidate
Next i
MsgBox m
End Sub
:
Find works best for most situations, below is the function i use that takes sheet ref as input and returns row number as type Long
Dim lLastRow As Long
lLastRow = LastUsedRow(shName)
Private Function LastUsedRow(sh As Worksheet) As Long
LastUsedRow = sh.Cells.Find(What:="*", After:=sh.Cells.Cells(1), _
LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, MatchCase:=False).Row
End Function
The simplest thing might be to use the specialcells method, as in range.specialcells(xllastcell). This returns the cell whose row number is the last row used anywhere in the spreadsheet, and whose column is the last column used anywhere in the worksheet. (I don't think it matters what "range" you specify; the result is always the last cell on the worksheet.)
So if you have data in cells B30 and X5 and nowhere else, cells.specialcells(xllastcell) will point to cell X30 (and range("A1").specialcells(xlastcell) will also point to cell X30).
Instead of:
LastRow = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
MsgBox ("The Last Row Is: " & LastRow)
use this:
LastRow = cells.specialcells(xllastcell).row
MsgBox ("The Last Row Is: " & LastRow)
After 35 attempts this is the code that I was able to hack into my original:
' Used to determine LastRow, LastColumn, LastCell, NextCell
Dim LastRow As Long
Dim LastColumn As Integer
Dim LastCell As Range, NextCell As Range
With Worksheets("Tracking")
' Find LastRow. Works Best. 1st and last cells can be empty
If WorksheetFunction.CountA(Cells) > 0 Then
'Search for any entry, by searching backwards by Rows.
LastRow = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
'Search for any entry, by searching backwards by Columns.
LastColumn = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
'MsgBox "Last Cell" & vbCrLf & vbCrLf & Cells(LastRow, LastColumn).Address
'MsgBox "The Last Row is: " & vbCrLf & vbCrLf & LastRow
'MsgBox "The Last Column is: " & vbCrLf & vbCrLf & LastColumn
End If
' Number of columns based on actual size of log range NOT MyAr(n)
Set NextCell = Worksheets("Tracking").Cells(LastRow + 1, (LastColumn - 10))
End With
This finds the "Real" Last Row and column and ignores any empty cells in Column A or J which seem to affect some of the LastRow snippets. I needed to make it ROWS instead of ROW and HAD the add the Offset portion as well. (-10) puts me back to Column "A" for my sheet and now I have removed Column "A" {the forced Place Holder "."} and have "Real" data there now. YAY for the "Hacking Code Cobbler".
Glad they pay me at work to learn this stuff. :) Solved this a while back. Just now got to update this post.