0

I am trying to fill a range of cells with a XLOOKUP formula using VBA.

I will be using a different file every day, so I would like to use a variable for the date portion of the filename.

I get

Run-time error 1004: Application-defined or object-defined error

in the last step of filling in column V with the XLOOKUP formula.

Dim lastRow As Long, filename As String, reportDate As String
    
    

Call getReportDate(reportDate) 'UserForm where user enters date of report
 
lastRow = ActiveSheet.Range("J" & Sheets("OCI").Rows.Count).End(xlUp).Row
    
filename = "report_name_" & reportDate & ".xlsx"
    
 
Range("V2:V" & lastRow).Select

Selection.Value = "=XLOOKUP(@A:A, ""[" & filename & "]Sheetname""!$L:$L, ""[" & filename & "]Sheetname""!$N:$N)"

Hard coding the filename works.

2
  • 1
    Range("V2:V" & lastRow).Formula= "=XLOOKUP(@A:A, [" & filename & "]Sheetname!$L:$L, [" & filename & "]Sheetname!$N:$N)" Commented Feb 14, 2024 at 22:57
  • 1
    Thank you! I had to add single quotes for the filename and sheet name. Here is the final solution that worked: Range("V2:V" & lastRow).Formula= "=XLOOKUP(@A:A, '[" & filename & "]Sheetname'!$L:$L, '[" & filename & "]Sheetname'!$N:$N)" Commented Feb 15, 2024 at 0:26

1 Answer 1

0

another method without using select (which is preferred) would be looping through Range("V2:V" & lastRow) like this:

Dim lastRow As Long, filename As String, reportDate As String
        
        

Call getReportDate(reportDate) 'UserForm where user enters date of report
 
lastRow = ActiveSheet.Range("J" & Sheets("OCI").Rows.Count).End(xlUp).Row
        
filename = "report_name_" & reportDate & ".xlsx"
        

Dim rng as range, c as range 
set rng = Range("V2:V" & lastRow) 
For each c in rng
c.Formula = "=XLOOKUP(@A:A, ""[" & filename & "]Sheetname""!$L:$L, ""[" & filename & "]Sheetname""!$N:$N)"

Next c
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.