SOLVED

Use VBA to Autofill a Row until the end of the number of data in another row

Copper Contributor

Hello,

 

I need some help with the following problem:

 

The Macro should select the first cell with the vlookup (AY2) and autofill the complete range in the column AY until the last row that contain data in the cell next to it (Column E). Column E is the cell that the vlookup refers to.

 

The situation looks like this:

 

2017-12-14_09h25_21.png

 The code that I have so far looks like this:


    Sheets(3).Select
    Range("AY2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-41],DennisAR!C[-50],1,0)"
    Selection.AutoFill Destination:=Range("AY2:AY1662")
    Range("AY2:AY1662").Select

 

The problem with this is, that the number of rows with data always change every week. So I cannot use a static row number of 1662.

 

I am looking for a way to make Destination:=Range("AY:AY1662) dynamic. In fact it has to refer to the number of rows with data in column E.

 

Thank you very much in advance,

Kai
   

 

 

81 Replies

Replace these lines of code:

Selection.AutoFill Destination:=Range("AY2:AY1662")
Range("AY2:AY1662").Select

With this:

Selection.AutoFill Destination:=Range("AY2:AY" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

Give it a try!

And provide me with any feedback!

best response confirmed by cuong (Microsoft)
Solution

@Haytham Amairah 

 

Hi Haytham Amairah,

 

I was facing similar issues and chanced upon this thread. If i have two columns (O and P) that i wish to autofill via VBA, do I amend the code from: 

 

Selection.AutoFill Destination:=Range("O2:P313")
Range("O2:P313").Select

 

to:

Selection.AutoFill Destination:=Range("O2:O" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

Selection.AutoFill Destination:=Range("P2:" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

 

Thanks Haytham,
This worked like a magic for me in no time.
Appreciate your knowledge and interest to share it.

@Haytham Amairah Dear Haytham, would you be able to amend my code so that it works the same way as OP's please?

 

I have to amend the ActiveCell.End(xlDown) part so that the formula (in column N) stops at the last row that contains data in column M. Thank you in advance.

 

ActiveCell.FormulaR1C1 = "=IF(RIGHT(RC[-8],1)=""A"",""f"",""m"")"
ActiveCell.Select
Selection.AutoFill Destination:=Range(ActiveCell, ActiveCell.End(xlDown))
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Selection.Copy
Range(ActiveCell).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

 

Regards,

Mike

Hi Mike,

 

Please try this one:

Sub test()

ActiveCell.FormulaR1C1 = "=IF(RIGHT(RC[-8],1)=""A"",""f"",""m"")"
Selection.AutoFill Destination:=Range("N1:N" & Range("M" & Rows.Count).End(xlUp).Row)
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

Application.CutCopyMode = False

End Sub

 

Hope that helps

 

@W4rcloud 

Hi

I am trying to build a macro to unprotect sheet, autofill columns from above and protect sheet again. I am using below formula however it is giving error. Can anyone help please?

Sub sbUnProtectSheet()

ActiveSheet.Unprotect "9999"

Set SourceRange = ActiveSheet.Range("B10:H10")
Set fillRange = ActiveSheet.Range("B11:H39")
SourceRange.AutoFill Destination:=fillRange
ActiveSheet.Protect "9999", True, True

End Sub

Thanks

Anil

@AnilChhabra

 

Hi,

 

It's better to post your question as a new conversation in the community.

If you can, provide us with a sample of the worksheet you're working on!

 

Regards

@Haytham Amairah 

 

Hey Haytham,

 

I'm really hoping you can point me in the right direction as well. 

 

I'm trying to do the same thing as OP, however I have blank rows above and to the left of my data and not sure if that is throwing it off. Below is a screenshot (had to switch all values to xxxx for privacy purposes), I want my Macro to create a new Column to the left of Column J in the screenshot, where a new Column J will be created that will house my formula beginning in the new Cell J6. I then want the Macro to extend this formula down the last row in any of the columns to the left of Column J, as they will all always be populated, however I have been tying everything to Column I in my troubleshooting.

 

Macro Help.PNG

 

Here is the snip of code that I know is causing the issue, with the problem rows likely being the three rows below my IF formula.

 

Sheets("Raw_Data").Select
ActiveCell.Offset(0, 8).Columns("A:A").EntireColumn.Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
ActiveCell.Offset(4, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = "MEASURE OUTCOME"
ActiveCell.Offset(1, 0).Range("A1").Select
ActiveCell.FormulaR1C1 = _
"=IF(AND(RC[-3]=""MET"",RC[-2]=""MET"",RC[-1]=""MET""),""Met"",""Not Met"")"
ActiveCell.Select
Selection.AutoFill Destination:=ActiveCell.Range("A1:A366")
ActiveCell.Range("A1:A366").Select
Selection.FormatConditions.Add Type:=xlTextString, String:="Met", _

 

Are you able to help me re-write this code to have the Macro fill the IF formula down to the last row of data rather than just the last cell in my current selection? The number of rows will change on a daily basis.

 

Thank you!

@Kai El Harrar 

Hi

If you wee to create a Table instead, Insert > Table, then your formula would automatically be inserted as you add rows to the Table, without the need for any VBA code.

@Steven1835

 

Hi,

 

Sorry about the late reply!

I think you need this one:

Sub FillFormulaDown()
'To check if the column is already exist
If Application.WorksheetFunction.IsFormula(Range("J5").Offset(1, 0)) Then
'skip
Else
Columns("J:J").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("J5").Value = "MEASURE OUTCOME"
End If

Range("J5").Offset(1, 0).Activate
ActiveCell.FormulaR1C1 = "=IF(AND(RC[-3]=""MET"",RC[-2]=""MET"",RC[-1]=""MET""),""Met"",""Not Met"")"
Selection.AutoFill Destination:=Range("J6:J" & Range("I" & Rows.Count).End(xlUp).Row)
ActiveCell.EntireColumn.AutoFit
End Sub

 

You will find it in the attached workbook.

Please test it and tell me what you thought.

 

Hope that helps

@Haytham Amairah 

 

Hi Haytham,

 

I have used your code in my macro when it imports from a text file and reorganizes the records. As part of it, it is supposed to copy down rows of a table as below:

 

ActiveCell.FormulaR1C1 = "=R[-1]C"
Range("A3").Select
Selection.AutoFill Destination:=Range("A3:A" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
Range("B3").Select
Selection.AutoFill Destination:=Range("B3:B" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

 

This works nicely but if there is a single line of record in the file, it copies the row but then it adds a second row, copies down the first row in column A and B then returns a VB Error as shown in the attached screenshot.

 

Any ideas how to deal with it?

 

Thanks

 

Nick

@NickNick33 

 

 Hi,

 

To figure out the problem, please provide a sample of the data you work on.

 

Regards

@Haytham Amairah 

 

Sure, it is attached. Th eoriginal file is a tsv file but the upload tool would not accept tsv so I had to change it to csv. You will need to change it to tsv for the Excel file to read it. 

 

Thank you 

@NickNick33

 

Hi,

 

This is what I got after opening your file:

Screenshot_1.png

 

Sorry, but the data isn't clear and I'm not sure what you're trying to do!

Based on your macro, you want to fill down Column A & B based on the number of rows in column E ??

@Haytham Amairah 

 

Here are the macro steps:

  • Imports the source file I provided,
  • adds 2 columns (Shipmentid and Name) in addition to the columns in the source file.
  • It takes what is in B1 in the source as Shipmentid and copies down the new column A
  • It takes what is in B2, copies down the new column B
  • Deletes the top rows up to the headings so that the whole file becomes one uniform table. 

This works fine except when there is a single in the source. I have attached both the Excel file and the different files that are used as the source. 

 

The macro is created to import the file called current.tsv. We just swap the files we want to import by renaming them "current.tsv". So I provided one sith single line and another with multiple. The one with multiple works fine but single one returns error as the VBA seems to have a problem with it. 

 

Curious situation. I hope this helps. 

 

@NickNick33

 

Hi,

 

After I reproduced this issue, I noticed that the error also occurs even if you have two records in the imported file.

 

If you have one or two rows in the imported file, there is no need to use the AutoFill method in the macro because all rows in the table are already filled.

If you use it in this case, there will be an error!

 

The solution is to make the code smart somehow to see if the imported file has less than three rows and if so, skip the autofill process to prevent the error.

 

This is what I suggest to overcome this issue:

Sub PrepFile()
'
' PrepFile Macro
'

'
Sheets("Sheet1").Select
Range("A1").Select
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=current;Extended Properties=""""" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [current]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "current"
.Refresh BackgroundQuery:=False
End With
Range("K10").Select
ActiveCell.FormulaR1C1 = "Shipment ID"
Range("L10").Select
ActiveCell.FormulaR1C1 = "Shipment Name"
Range("B2").Select
Selection.Copy
Range("K11").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B3").Select
Application.CutCopyMode = False
Selection.Copy
Range("L11").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Rows("10:10").Select
Application.CutCopyMode = False
Selection.Copy
Rows("1:1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Rows("2:10").Select
Range("A10").Activate
Application.CutCopyMode = False
Selection.Delete Shift:=xlUp
Columns("K:L").Select
Selection.Cut
Columns("A:A").Select
Selection.Insert Shift:=xlToRight

If Application.WorksheetFunction.CountA(Range("E:E")) - 1 = 1 Then
Range("A1").Select
Exit Sub
ElseIf Application.WorksheetFunction.CountA(Range("E:E")) - 1 = 2 Then
Range("A3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R[-1]C"
Range("B3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R[-1]C"
Range("A1").Select
Exit Sub
End If

Range("A3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R[-1]C"
Range("B3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R[-1]C"
Range("A3").Select
Selection.AutoFill Destination:=Range("A3:A" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
Range("B3").Select
Selection.AutoFill Destination:=Range("B3:B" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
Range("A1").Select
End Sub

 

Please replace your old macro with it.

 

Hope that helps

@Haytham Amairah 

What do I have to add if the source isn't in the same worksheet?

 

Thanks

@To31416

 

What's the source?
Please explain the problem well
!

1 best response

Accepted Solutions
best response confirmed by cuong (Microsoft)
Solution

@Haytham Amairah 

 

Hi Haytham Amairah,

 

I was facing similar issues and chanced upon this thread. If i have two columns (O and P) that i wish to autofill via VBA, do I amend the code from: 

 

Selection.AutoFill Destination:=Range("O2:P313")
Range("O2:P313").Select

 

to:

Selection.AutoFill Destination:=Range("O2:O" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

Selection.AutoFill Destination:=Range("P2:" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select

 

View solution in original post