I would like to find the last row in a range that I have selected so that my code is more dynamic and less likely to break if I exceed the range.
I am unsure of the syntax to use.
Instead of P4201, I would like to select the last row with a value within column P, whatever that may be.
Selection.AutoFill Destination:=Range("P2:P4201")
I am just unsure of the last syntax to select the last row with a value with P. Instead of doing P10000, I would like to make it cleaner.
The below macro counts up to the last filled cell in column P, and selects the full range from P2 until P-end.
Sub Select_Range()
Dim I As String
I = Sheet1.Range("P" & Rows.Count).End(xlUp).Row 'Determine last filled cell and count rows
Sheet1.Range("P2" & ":P" & I).Select 'select full filled range in column P.
End Sub
Let me know if this is what you're looking for.
Related
IF(ISBLANK(B5),"",IF(ISBLANK(O5)=TRUE,"Missing PSD",TODAY()-O5))
This is my formula that calculates the difference between the date in column O and current date. My first filled row with values is 5. The row in which the formula calculation is being done is AC.
I want to automatically calculate this until the last filled row and the row values should also increment like it does while dragging down.
I am not good with VBA so any help would be highly appreciated.
Try the next code, please:
Sub testFilFormulaDown()
Dim sh As Worksheet, lastRow As Long
Set sh = ActiveSheet 'use here the necessary sheet
lastRow = sh.Range("O" & rows.count).End(xlUp).row 'chosen O:O column, being involved in the formula...
sh.Range("AC5:AC" & lastRow).Formula = "=IF(ISBLANK(B5),"""",IF(ISBLANK(O5)=TRUE,""Missing PSD"",TODAY()-O5))"
End Sub
In order to properly calculate the last row, you must choose a fully filled column (A:A, C:C etc.). I used one involved in the formula, but since there is a check for blank cells, column O:O could not be the most appropriate one...
Need a little help here.
In the "Data" Tab I want to copy values in column "c2:c1000" and paste in column "a1" of another Tab.
This is what i have so far,
Dim x As Long
Dim lastRow As Long
lastRow = Worksheet("Data").Cells(3, Columns.Count).End(xlUp).Column
For x = 1 To lastRow
If Worksheets("Sheet2").Cells(2, "A") = "" Then
Worksheets("Data").Range("c2:c1000").Copy Destination:=Worksheets("Sheet2").Range(1, "A")
Sheets("Sheet2").Range("A1").Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
Else
Worksheets("Data").Range("c2:c1000").Copy Destination:=Worksheets("Sheet2").Cells(2,
Columns.Count).End(xlToLeft).Offset(, 1)
'Sheets("Sheet2").Range("A1").Value = Format(Now, "mm/dd/yyyy HH:mm:ss") --> can't figure how to increment this as this will need to be on the subsequent empty column
End If
Next
End Sub
Your help will be greatly appreciated!
Thank you.
Pasting values first into range A1 and down and then next time to cell B1 and so on, leaves no space for the timestamp to A1, B1 etc. So, I assume that you would like to paste the random values to row 2. So cells A1, B1, ... are left for the timestamp.
Inside the With statements we can refer to properties of the wsAudit so we can replace the "Worksheets("Audit")." reference with just "."
The column.count expression just checks the amount of columns in the worksheet.
The expression .Cells(2, Columns.Count) just points to last cell in the row 2.
The .End(xlToLeft).Column then looks from this column to left and is supposed to find the last not empty cell on this row. It's basically the same idea that in Excel's sheet you would go to cell XDF2 and hit CTRL+Arrow Left from keyboard.
But instead of activating the cell we just want to get the columns index number and then add 1 (the new column) and save it into variable. Now the new column is known.
The expression Range(.Cells(2, newColAudit), .Cells(1000, newColAudit)).Value is really the same as e.g. Range("B2:B1000"), but with this we can use the row and column index numbers instead. This is useful as the column number varies.
And as Samuel pointed out the copy paste operation can be avoided by setting the areas equal.
Dim wsAudit As Worksheet
Dim newColAudit As Long
Set wsAudit = Worksheets("Audit")
With wsAudit
newColAudit = .Cells(2, Columns.Count).End(xlToLeft).Column + 1
Range(.Cells(2, newColAudit), .Cells(1000, newColAudit)).Value = Worksheets("Data").Range("C2:C1000").Value
.Cells(1, newColAudit).Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
End With
Much like your LastRow* variable for your source sheet, create a LastColumn variable for your destination sheet, which will find the last used column the same way you are finding your last used row.
Like so:
Dim LastColumn As Long
LastColumn = Sheets("Audit").Cells(1, Columns.Count).End(xlToLeft).Column
Then use the variable like so:
Destination:= Worksheets("Audit").Cells(1, LastColumn)
It seems that your code contradicts your question too, in your question you explained the data will be written to the Audit sheet in row 1, using the next column each time but your code looks for values in row 2 in your If statement:
If Worksheets("Audit").Cells(2, "A") = "" Then is the same as If Worksheets("Audit").Range("A2") = "" Then.
If you mean to check the first row, change the 2 to 1.
To help improve your codes efficiency:
(Also see the link to 'how to avoid select' in that question):
You can achieve 'copy/paste' without actually using the 'copy' and 'paste' methods by assigning the value of one range to the other, as example, like so:
Worksheets("Audit").Cells(1, LastColumn).Resize(999, 1) = Worksheets("Data").Range("c2:c1000").Value
Note: Change the Resize Property rows to suit the source range (in this case you are wanting to move values from C2:C1000).
*The LastRow variable is a bit confusing, as it is looking for the last used column in row 3.
If it's meant to find a column, consider renaming it to avoid confusion later on in debugging.
If it's meant to find the last row, try like this:
LastRow = Worksheet("Data").Cells(Rows.Count, 1).End(xlUp).Row
I have an issue with using a formula that contains a fixed cell in VBA. The issue comes when the row number of the variable in the new data changes.
The issue is explained using a simple example as follow. I hope you find it understandable.
Let's say I have a column of numbers (Time) and I want to multiply them by a variable in a cell (The cell below Variable in the following table, $A$2).
First result from first raw data:
The results in the table are calculated using the following formula "=R2C1*RC[-1]" in vba
Now in the next calculation, the row number and variable change and the part of the formula which is using a fixed cell cause problem.
Second raw data to be processed
Because it does not update the row number and use the old row number. I want it to find its location like the second part of the formula (B2 changes to B7).
Thank you for your help!
Cheers,
Aryan
you should reference the found cell row in your formula
ActiveCell.FormulaR1C1 = "=R" & ActiveCell.Row + 1 & "C1*RC[-1]"
but you should also avoid the Activate/ActiveXXX/Select/Selection pattern since is prone to have you quickly lose control over the actually active thing
finally you an use a loop to find all "Time" occurrences (see Here for more info about the pattern)
Option Explicit
Sub main()
Dim f As Range, firstCell As Range
With Worksheets("myWorksheetName") ' reference your worksheet (change myWorksheetName to your actual sheet name)
With .Range("B1", .Cells(.Rows.Count, "B").End(xlUp)) 'reference its column B cells from row 1 down to last not empty one
Set f = .Find("Time", LookIn:=xlValues, lookat:=xlWhole) 'search referenced range for first occurrence of "time"
If Not f Is Nothing Then ' if found...
Set firstCell = f ' store first occurrence cell
Do
f.Offset(1, 1).Resize(4).FormulaR1C1 = "=R" & f.Row + 1 & "C1*RC[-1]" ' populate the range one column to the right of found cell and 4 rows wide with the formula containg the reference of found cell row +1
Set f = .FindNext(f) ' serach for the next "Time" occurrence
Loop While f.Row <> firstCell.Row ' loop till you wrap back to initial occurrence
End If
End With
End With
End Sub
The notation R2C1 is an absolute reference to row 2, column 1.
If you want a reference that is relative to the current cell, you need to use relative reference notation.
RC[-1] points to a cell in the current row and one column to the left
R[1]C points to a cell one row down from the current cell and in the same column as the current cell.
Google for "R1C1 reference". You will find many articles, for e.g. https://smurfonspreadsheets.wordpress.com/2007/11/12/r1c1-notation/
Hello from an unexperienced vba user.. I'm having trouble with the code for autofill to the last row when trying to use named ranges for the column. Everything seems to work fine when I use a hard coding for the column, in this case Column CW, and what I need is to replace this column CW with a named range so that the macro will still work when adding or deleting columns in the worksheet.
I used the following named ranges:
First_Date: This is the header cell of one of the columns (in this case AP5)
Second_Row: This is the range of columns I want to copy the formulas from (AP7:CW7)
Second_Cell: The cell where I want to start to autofill (AP7)
Last_Column: This is column CW that I want to use in the code. Autofill would be up to this column and down to the last row.
After searching in different threads, I came up with the following code that seems to work fine. How can I change column CW to a named range? Or do I need to change the code?
Dim Lr As Integer
Lr = Range("First_Date").End(xlDown).Row 'Searching last row
Rows(Lr).Insert Shift:=xlDown 'Inserting new row
Range("Second_Row").AutoFill Destination:=Range(Range("Second_Cell"), Range("CW" & Lr))
Can anyone assist me here please?
This will get the job done :-)
Sub RangerFiller()
'The Cell that holds the formula B1
OriginalFormula = Cells(1, 2).Formula
'copies formula down to the last column next to B but use can use another column as
'a counting column....the column that hold the last value
Range("B2:B" & Cells(Rows.Count, "A").End(xlUp).Row).Formula = OriginalFormula
End Sub
Someone gave me the solution:
Change
Range("CW" & Lr)
To
Cells(Lr, Range("Last_Column").Column)
I faced a similar problem because I don't want to hard code the cell reference. I found this solution below to be useful, by using "& ______ &" to replace the cell number that can be calculated using input box or formula.
Eg.
cell1 = last row of column A
Range("CW " & cell1 &" :CW & Lr),
where cell1 = any number that can be added via input box/formula.
Hope this helps!
I am developing a dashboard in excel. And I am looking for calculating row count. (How many records are present) ..
Since there are some blank cells I thought to go from bottom to up. I use the following
Range("A1048576").Select
Selection.End(xlUp).Select
After this execution the active cell is at A113 which means the row count is 113.
My question is how to get this number 113 from the active cell?
You can use this:
Dim lastrow as Long
lastrow = Cells(Rows.Count,"A").End(xlUp).Row
lastrow will contain number of last empty row in column A, in your case 113
Here is what I usually use for that:
lastrow = WorksheetFunction.CountA(Columns("A:A"))
This will return the number of non-empty cells in Column "A" which is what I think you're after. Hope this helps.
The best way to get the count of rows/records (in most cases) is to use .UsedRange.Rows.Count. You can assign the return value to a variable like this:
lastRow = Sheets(1).UsedRange.Rows.Count
If you use a function that includes a column (such as column A) as shown in other examples, that will only get you the count of rows in that column, which may or may not be what you're going for. One caveat: if you have formatted rows below your last row with a value then it will return that row number.
If there is a slight chance that the last row of the worksheet is not empty, you should add an IsEmpty() check to #simoco 's solution. Therefore; following is a function that returns the last used row and check if the last row of the worksheet is empty:
Function lastRow(WS As Worksheet, iColumn As String) As Long
If Not IsEmpty(WS.Range(iColumn & WS.Rows.Count)) Then
lastRow = WS.Rows.Count
Else
lastRow = WS.Range(iColumn & WS.Rows.Count).End(xlUp).Row
End If
End Function