Forum Discussion
Define variable in my VBA to clean my code (error)
Hello,
I would like to define variable in the top of my VBA to reference file and range (column) to make then Index/match function. Defining variable at the top of my code will be more convenient to update my code later on.
However, I always face an error message on this line:
Range("B2:B" & NBrow1).FormulaR1C1 = "=INDEX(" & MDART_G2.Address(External:=True) & ",MATCH(RC1," & MDART_CODE.Address(External:=True) & ",0))"
Thank you in advance for your support.
Anthony
CODE:
Sub Reformatage_report_G2_AFO_TEST()
Dim wb2 As Workbook
Dim cheminFichier2 As String
Dim wb2Name As String
cheminFichier2 = "https://sodiaal.sharepoint.com/sites/DAG-EquipeAchatsPackaging/Documents partages/General/PROC-OP/BDD ARTICLES G2/DB_article_G2.xlsx"
Set wb2 = Workbooks.Open(cheminFichier2)
Windows("extract.xlsx").Activate
'////////////////////////////////////////////////////////////////
Dim MDART_G2 As Range
Dim MDART_CODE As Range
Set MDART_G2 = wb2.Sheets("2. Référenciel Article").Range("G:G")
Set MDART_CODE = wb2.Sheets("2. Référenciel Article").Range("A:A")
'////////////////////////////////////////////////////////////////
Dim NBrow1 As Long
With ActiveSheet
NBrow1 = Range("A" & .Rows.Count).End(xlUp).Row
Range("B1").Select
ActiveCell.FormulaR1C1 = "SCOPE G2"
Range("B2:B" & NBrow1).FormulaR1C1 = "=INDEX(" & MDART_G2.Address(External:=True) & ",MATCH(RC1," & MDART_CODE.Address(External:=True) & ",0))"
End With
End Sub
Steve_SumProductCom
Thank you very much, I did a small adjustment to your code because it was taking the col 1 and 7 of the extract.xlsx instead of the source file (see print screen below).But with the code below, it is working perfectly! Thank you. Very helpful.
.Range("B2:B" & NBrow1).FormulaR1C1 = "=INDEX(" & MDART_G2.Address(External:=True, ReferenceStyle:=xlR1C1) & ",MATCH(RC[-1]," & MDART_CODE.Address(External:=True, ReferenceStyle:=xlR1C1) & ",0))"
- Steve_SumProductComIron Contributor
AnthonyC1730 In that line, the property FormulaR1C1 is expecting to get references in R1C1 format, but your references are in A1 format (from the lines below):
Set MDART_G2 = wb2.Sheets("2. Référenciel Article").Range("G:G")
Set MDART_CODE = wb2.Sheets("2. Référenciel Article").Range("A:A")
Does it work properly if you replace "FormulaR1C1" with "Formula" or "Formula2"?
- AnthonyC1730Copper Contributor
Steve_SumProductCom
I also tried with the piece of code (R1C1 format):Set MDART_G2 = wb2.Sheets("2. Référenciel Article").Range("C7")
Set MDART_CODE = wb2.Sheets("2. Référenciel Article").Range("C1")but I still have the same error when I execute the VBA at this line:
.Range("B2:B" & NBrow1).FormulaR1C1 = "=INDEX(" & MDART_G2 & ",MATCH(RC[-1]," & MDART_CODE & ",0))"
Thank you
- Steve_SumProductComIron ContributorPlease share a screen shot or the exact text of the error message.