Loop that replicate my formula until last cell of my row - excel

My aim is to have a formula that fills the empty cells with the previous Q. question, until the last non empty cell (see picture)
The range is the last non empty cell of my row.
For now my code looks like this :
Sub Range_End_Exemple()
Dim cell_target As Range
ActiveCell.FormulaR1C1 = "=+IF(ISBLANK(R[-2]C)=TRUE,RC[-1],R[-2]C)"
Set cell_target = Worksheets("dataset Feedback forms").Range(Cells(1, Columns.Count).End(xlToLeft).Select Type:xlFillDefault
End Sub
Thanks for you help if you have any suggestion.

The sub below is only based the picture you attached.
Sub test()
Dim LastCol As Range
Dim rg As Range
Dim cell As Range
With ActiveSheet
Set LastCol = .Cells(2, Columns.Count).End(xlToLeft).Offset(-1, 0)
Set rg = .Range("D1", LastCol)
For Each cell In rg.SpecialCells(xlCellTypeConstants)
If cell.End(xlToRight).Column = .Columns.Count Then
Range(cell, LastCol).Value = cell.Value
Else
Range(cell, cell.End(xlToRight).Offset(0, -1)).Value = cell.Value
End If
Next
End With
End Sub
The code assumed that nothing is change in "header-2".
The "header-1" will start in cell D1.
How many "type of header-1" is unknown.
The last column used in "header-2" is unknown.
The process:
it get the cell of the last column used in "header-2" then offset the row to -1 then have it as the LastCol variable. The LastCol cell is used to mark the end of "header-1".
then it get the range of the "header-1" into rg variable.
then it loop the cells of the rg which has value,
copy the cell till the last empty cells to the right (before the next header type of "header-1").
since the last header type of "header-1" will have no border, then it will check if the last empty cell column to the right value = the worksheet columns count ... then it use the LastCol variable as the border.
Based on seeing your image attachment, the thing which I'm unable to understand on what you want is : you use a formula for your "header-1" ?

so I'd imagine something like this:
lrow = Cells.Find("*", Cells(1, 1), xlValues, xlPart, xlByColumns, xlPrevious, False).Column ' <-- this gives you the last column blank
nextblank = Cells.Find("", Cells(1, 1), xlFormulas, xlByColumns, xlNext, False).Column ' <-- this gives you the FIRST blank column number
ltr = Split(Cells(1, nextblank - 1).Address, "$")(1) ' <-- this gives you the letter
aux = Range(ltr & "1") ' <-- this is the value you need to copy
After the first nextblank statement you need to use this to iterate
nextblank = Cells.Find("", Cells(1, nextblank), xlFormulas, xlByColumns, xlNext, False).Column
Using those values -> lrow doesn't change, it's your final destination
nextblank,ltr and aux values changes after you copy
Hope it helps!

This will do what you appear to want from your image:
Sub Propagate()
Dim lastCol As Integer
With Worksheets("dataset Feedback forms")
lastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column
With .Cells(1, 4).Resize(1, lastCol - (4 - 1)).SpecialCells(xlCellTypeBlanks)
.FormulaR1C1 = "=RC[-1]"
.Value2 = .Value2
End With
End With
End Sub

Related

Find last row of column without including blank cells

I have a problem with my code. In the data there are 60 rows, and in column T, there are 57 rows which have value i.e that are not blank. Cells 58,59,60 are blank. I am trying to find the last row for Column T. Whenever I run the code, it always gives me 60 instead of 57.
Here is my code
Dim lastrow As Long
lastrow = Cells(Rows.Count, 20).End(xlUp).Row
MsgBox "The Last Row of Data for Column T " & lastrow
Range("B2:T" & lastrow).SpecialCells(xlCellTypeVisible).Select
With Selection.Font
.Color = -16776961
.TintAndShade = 0
Another Last Row Issue
Intro
An empty cell is an empty cell.
A blank cell is either an empty cell, a cell containing a formula evaluating to "", a cell containing a ', etc. (if any).
If you want to select the non-blank cells, you have to use the xlValues parameter of the LookIn argument of the Find method. The parameter of this argument is saved each time you use the method. So by sheer chance, the accepted answer is working correctly since the parameter is set to xlValues (which is not the default value).
'Proper' data does not contain blank rows at the bottom, so most often the xlFormulas parameter of the LookIn argument is the way to go.
In-depth studying of the Find method is crucial to revealing the countless possibilities.
The Find method may (will) fail if the worksheet is filtered and additionally may (will) fail with the xlValues parameter when rows are hidden (the xlFormulas parameter will handle hidden rows correctly).
Tip
This is a link to Siddharth Rout's legendary answer to the question Error in finding last used cell in Excel with VBA which is worth (highly recommended) studying as is the following.
The Examples
Option Explicit
' All four solutions assume that there are no hidden or filtered rows.
Sub testLastRowBeginner()
Const FirstRow As Long = 2
Dim lCell As Range
Set lCell = Columns(20).Find("*", , xlValues, , , xlPrevious)
' Assuming that there is data at least in row 2 ('FirstRow') of the column.
Dim LastRow As Long: LastRow = lCell.Row
MsgBox "The Last Row of Data for Column T " & LastRow
With Range("B" & FirstRow & ":T" & LastRow).SpecialCells(xlCellTypeVisible)
With .Font
.Color = -16776961
.TintAndShade = 0
End With
End With
End Sub
Sub testLastRowIntermediate()
Const FirstRow As Long = 2
Dim lCell As Range
' For non-empty cells (most often):
'Set lCell = Columns(20).Find("*", , xlFormulas, , , xlPrevious)
' For non-blank cells which is most probably your case,
' because you have formulas evaluting to "":
Set lCell = Columns(20).Find("*", , xlValues, , , xlPrevious)
Dim LastRow As Long
If Not lCell Is Nothing Then
LastRow = lCell.Row
If LastRow < FirstRow Then
MsgBox "The last row is smaller then the first.", _
vbCritical, "Last Row Too Small"
End If
Else
MsgBox "The column range is blank.", vbCritical, "No Last Cell"
Exit Sub
End If
MsgBox "The Last Row of Data for Column T " & LastRow
With Range("B" & FirstRow & ":T" & LastRow).SpecialCells(xlCellTypeVisible)
With .Font
.Color = -16776961
.TintAndShade = 0
End With
End With
End Sub
Sub testLastRowAdvanced()
Const First As String = "T2"
With Range(First)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlValues, , , xlPrevious)
If lCell Is Nothing Then
MsgBox "No data.", vbExclamation, "Fail"
Exit Sub
Else
LastRow = lCell.Row
End If
End With
MsgBox "The Last Row of Data for Column T " & LastRow
With Range("B" & FirstRow & ":T" & LastRow).SpecialCells(xlCellTypeVisible)
With .Font
.Color = -16776961
.TintAndShade = 0
End With
End With
End Sub
Sub testLastRowExpert()
Const Cols As String = "B:T"
Const FirstRow As Long = 2
Dim rg As Range
With Columns(Cols).Rows(FirstRow)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - FirstRow + 1) _
.Find("*", , xlValues, , xlByRows, xlPrevious)
If lCell Is Nothing Then
'MsgBox "No data.", vbExclamation, "Failure"
Exit Sub
End If
Set rg = .Resize(lCell.Row - .Row + 1)
End With
'Debug.Print rg.Address
With rg.SpecialCells(xlCellTypeVisible)
With .Font
.Color = -16776961
.TintAndShade = 0
End With
End With
End Sub
You can use the VBA function find() to solve the problem using the following code
lastRow = ActiveSheet.Range("T:T").Find("*", searchOrder:= xlByRows, SearchDirection:= xlPrevious).Row
"*" means find any value, so it is possible to locate any cell with a value.
searchORder:= xlByRows means that the function will find the value row by row.
searchDirection:= xlPrevious means that the function will look from the end of the sheet to the beginning of the sheet.
So the entire function's parameter means that to find a cell with value in column T, row by row from the end of the sheet to the top of the sheet.
Use .Row attribute to obtain the row number, use +1 to find the empty row.

Fill in the entire column according to the last data in the table - Does not work

I have a formula in Column A2.
I have a table similar to this:
Formula
Note
Datum
I am very happy because I am
Years
years old
=CONCATENATE(TEXT(C2;"dd-mm-yyyy");$D$1;E2;$F$1)
Any word, TEXT
01.04.2021
21
Autofill
Any word, TEXT 2
01.04.2021
25
I want to transfer it and use it automatically for the whole column. However, I tried possible and impossible ways to do it, but none of them worked. I also looked at forums such as here:
I don't have all the data filled in the table, so I want "excel" to look for the last row in which the record is and try to calculate the formula and return it to the last cell in column A.
Thank you in advance for all the help
(The formula joins the text together) =CONCATENATE(TEXT(C2;"dd-mm-yyyy");$D$1;E2;$F$1)
Sub AutofilCol()
' Apply to the entire column Autofill
Range("A1").Offset(1, 0).Activate
ActiveCell.FormulaR1C1 = _
"=CONCATENATE(TEXT(RC[2],""dd-mm-yyyy""),R1C4,RC[4],R1C6)"
' AutoFill
Selection.AutoFill Destination:=Range("A2:A").End(xlDown).Row
ActiveCell.EntireColumn.AutoFit
End Sub
It looks like this is what you want to do:-
Sub AutofillCol()
Dim Rl As Long ' last used row in column C
Dim Rng As Range
Rl = Cells(Rows.Count, "C").End(xlUp).Row
Set Rng = Range(Cells(2, "A"), Cells(Rl, "A"))
Rng.FormulaR1C1 = "=CONCATENATE(TEXT(RC[2],""dd-mm-yyyy""),R1C4,RC[4],R1C6)"
End Sub
Copy Formulas (Defining a Range)
In this case, there is no need to Activate (or Select) anything neither is the use of AutoFill (FillDown).
Let's say the first solution is the most flexible (reliable) but also the most complex. To better understand it, see the ranges at the various stages of the code printed in the Immediate window (CTRL+G). The flexibility is in the option to use any first cell address e.g. C5, D10, etc. and it will still work.
Depending on your data, you might easily get away with the remaining two solutions.
I didn't include any solution using End since you got that covered by another post.
Option Explicit
Sub copyFormulas()
Const First As String = "A1"
Dim ws As Worksheet: Set ws = ActiveSheet
Dim fCell As Range ' Last Cell in First Row Range
Dim frg As Range ' First Row Range of Table Range
With ws.Range(First)
Set fCell = .Resize(, .Worksheet.Columns.Count - .Column + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If fCell Is Nothing Then Exit Sub
Set frg = .Resize(, fCell.Column - .Column + 1)
Debug.Print "First", fCell.Address, frg.Address
End With
Dim tCell As Range ' Last Cell in Table Range
Dim trg As Range ' Table Range
With frg
Set tCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
Set trg = .Resize(tCell.Row - .Row + 1)
End With
Debug.Print "Table", tCell.Address, trg.Address
Dim drg As Range ' Destination Range
Set drg = trg.Columns(1).Resize(trg.Rows.Count - 1).Offset(1)
Debug.Print "Destination", drg.Address
drg.FormulaR1C1 = "=CONCATENATE(TEXT(RC[2],""dd-mm-yyyy""),R1C4,RC[4],R1C6)"
' Or.
'drg.Formula = "=CONCATENATE(TEXT(C2,""dd-mm-yyyy""),$D$1,E2,$F$1)"
End Sub
Sub copyFormulasUsedRange()
With ActiveSheet.UsedRange.Columns(1)
.Resize(.Rows.Count - 1).Offset(1).FormulaR1C1 _
= "=CONCATENATE(TEXT(RC[2],""dd-mm-yyyy""),R1C4,RC[4],R1C6)"
End With
End Sub
Sub copyFormulasCurrentRegion()
With ActiveSheet.Range("A1").CurrentRegion.Columns(1)
.Resize(.Rows.Count - 1).Offset(1).FormulaR1C1 _
= "=CONCATENATE(TEXT(RC[2],""dd-mm-yyyy""),R1C4,RC[4],R1C6)"
End With
End Sub

Copy offset range in for loop

I have a script that loops through a list of ID numbers to check if there is a matching ID in another list, if there is a matching ID, it copies the email in the adjacent column and pastes it in another range. I am having trouble copying an offset range since it doesn't appear to be pasting any values. This script is not throwing any errors:
Sub tryThis()
Dim lookHere As Range, pasteHere As Range, cell As Range, searchList As Range
Set List1 = Range(Range("A1"), Range("A1").End(xlDown))
Set List2 = Range(Range("C1"), Range("C1").End(xlDown))
For Each cell In List1
Set found = List2.Find(what:=cell, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not found Is Nothing Then
cell.Offset(, 1).Resize(, 1).Copy Destination:=Cells(Rows.Count, "G").End(xlUp)
End If
Next cell
End Sub
This:
cell.Offset(, 1).Resize(, 1).Copy _
Destination:=Cells(Rows.Count, "G").End(xlUp)
will copy the value into the same cell each run, since End(xlUp) takes you to the last occupied cell in the column, not the first empty cell. You need to Offset() one down to the next empty position. Also can do this with a direct value assignment:
Cells(Rows.Count, "G").End(xlUp).Offset(1, 0).Value = cell.Offset(0, 1).Value
Edit: if the cell you want to copy is from List 2 then:
Cells(Rows.Count, "G").End(xlUp).Offset(1, 0).Value = found.Offset(0, 1).Value

How can I find last used column in formatted table?

I am trying to get the last used column in my formatted table and insert a value. But it's always returning the very last (=empty) column inside the table. See picture below for understanding:
For some reason, the text "- seit -" is placed into the column "10.Besitzer" in column 16 whereas it should have been put into "1.Besitzer" in column 7.
My code looks as following:
LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row + 1 '+1 to go to next empty row
'here it adds values in empty row, starting from column 1(ID) until column 6(IT).
'I left out this part of code.
LastCol = ws.Cells(LastRow, Columns.Count).End(xlToLeft).Column 'Search for last column
ws.Cells(LastRow, LastCol).Value = "- seit -" 'place text into last column
If have a feeling its causing problems because its a formatted table but I am not sure about that. I am very thankful for any help.
Yes it stops because its a table. Check if value exist and if no again check for last column same way only not Columns.Count but from the LastColumn.
Read the comments and adjust it to fit your needs
Public Sub InsertColumnValue()
' Set a reference to the table
Dim targetTable As ListObject
Set targetTable = Range("TableName").ListObject
' Find last row in column A
Dim lastRow As Long
lastRow = targetTable.DataBodyRange.Cells(targetTable.DataBodyRange.Rows.Count, "A").End(xlUp).Row - targetTable.HeaderRowRange.Row
' Add data to next empty row
' Do something
' Check if last column in last row is empty
Dim lastColumn As Long
If targetTable.DataBodyRange.Cells(lastRow, targetTable.DataBodyRange.Columns.Count).Value = vbNullString Then
lastColumn = targetTable.DataBodyRange.Cells(lastRow, targetTable.DataBodyRange.Columns.Count).End(xlToLeft).Column
Else
lastColumn = targetTable.DataBodyRange.Columns.Count
End If
' Add value to next empty column in next empty row
targetTable.DataBodyRange.Cells(lastRow + 1, lastColumn + 1).Value = "- seit -"
End Sub
Use the next function, please:
Function LastUsedColInTable(tbl As ListObject, iRow As Long) As Long
Dim C As Range
With tbl.Range.rows(iRow)
Set C = .Find(what:="*", After:=.cells(1), LookIn:=xlValues, _
searchorder:=xlByColumns, SearchDirection:=xlPrevious)
If Not C Is Nothing Then
LastUsedColInTable = C.Column
Else
LastUsedColInTable = 1
End If
End With
End Function
It can be tested in this way:
Sub testLastColInTable()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects(1)
Debug.Print LastUsedColInTable(tbl, 2)
End Sub

Select range with VBA - got stuck

I got little project in VBA and stuck on below topic.
I need to select range from searched value to first empty cell in H column.
Selected range should looks like this
Selected Range in Excel:
I searched for specific value in column A and if I found it it's being set as first cell in range. ( It works)
Then I need to find last cell in range which is first empty cell in last column.
This is what I've found and try to use
Sub Button()
Dim StringToFind As String
StringToFind = Application.InputBox("Enter string to find", "Find string")
Worksheets("SS19").Activate
ActiveSheet.Range("A:A").Select
Set cell = Selection.Find(What:=StringToFind, After:=ActiveCell, _
LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
cell.Select
With Worksheets("SS19")
Set rr = .Range(ActiveCell, .Cells(.Rows.Count, "H").End(xlUp))
With rr
rr.Parent.Range(.Cells(1, "A"), .Cells(.Rows.Count, "H").End(xlUp).Offset(1, 0)).Select
End With
End With
If cell Is Nothing Then
Worksheets("SS19").Activate
MsgBox "String not found"
End If
I tried to searched for first empty cell in prevously selected range so it won't search the whole column but it doesn't work.
Try this...
Dim StringToFind As String
StringToFind = Application.InputBox("Enter string to find", "Find string")
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet2")
With ws
Dim findCel As Range
Set findCel = .Range("A:A").Find(StringToFind, , , xlWhole, , , False, , False)
Dim lRow As Long
lRow = .Range(findCel.Address).Offset(, 7).End(xlDown).Row + 1
Dim rr As Range
Set rr = .Range("A" & findCel.Row & ":" & "H" & lRow)
rr.Select
End With
I find that using the worksheet's match function is easier than Range.Find when searching a single column.
Option Explicit
Sub Button()
Dim stringToFind As String, m As Variant
Worksheets("SS19").Activate
stringToFind = Application.InputBox("Enter string to find", "Find string", Type:=xlTextValues)
With Worksheets("SS19")
m = Application.Match(stringToFind, .Range("A:A"), 0)
If Not IsError(m) Then
If Not IsEmpty(.Cells(m + 1, "H")) Then
.Range(.Cells(m, "A"), .Cells(m, "H").End(xlDown).Offset(1)).Select
Else
.Range(.Cells(m, "A"), .Cells(m, "H").Offset(1)).Select
End If
End If
End With
End Sub
Using .End(xlDown) could be problematic if the first cell under row m in column H was blank and this should be checked for or you might find the selection reaching too far, possibly all the way down to the bottom of the worksheet. Checking for a non-blank cell will catch this potential problem.

Resources