简体   繁体   中英

Excel vba autofill coding

I am currently using vba to perform the following tasks. So I copied data from sheet1 and pasted it in sheet2. There was already data in sheet2, so I pasted below the existing data. Now I need to perform a vlookup to get data from sheet3 to sheet2 for certain columns, so the vlookup would send the data below the existing data on sheet2. I have the following codes below

Range(“F1”).End(xldown).Offset(1).Select
ActiveCell.FormulaR1C1 = “=Vlookup(RC[7],Monitor_Report[#All],4,FALSE)”

ActiveCell.AutoFill Destination:=Range(ActiveCell.Address & “:” & ActiveCell.End(xlDown).Offset(-1,0).Address)

So currently even tho, the next row has no data, it still auto fills and results in #N/A after the cell where the vlookup occurs first. i do not want the autofill to happen if the next row has no data. Can anyone assist me to modify this code?

If you're set on using the manual way of .Select and .AutoFill , I'd just add an IFNA -statement to your formula:

Sub test()
  Dim ws As Worksheet
  Set ws = ThisWorkbook.Worksheets("Sheet1")

  ws.Range("F1").End(xlDown).Offset(1).Select
    
  Dim fRow As Long

  With ws
    fRow = .Cells(.Rows.Count, ws.ListObjects("Monitor_Report").DataBodyRange.Column).End(xlUp).Row
    fAdr = ActiveCell.Column
  End With

  adr_ = ws.Cells(fRow, fAdr).Address

  ActiveCell.Value = "=IFNA(VLOOKUP(M3,Monitor_Report[#All],4,FALSE),"""")" '
  ActiveCell.AutoFill Destination:=ws.Range(ActiveCell.Address & ":" & adr_)


End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM