更改公式中的引用对于循环中的每个单元格
我有一个子程序将索引/匹配应用到7个单元格的范围内,查找一个命名范围,并将不同的索引值应用到每个单元格中的公式。
我有一个工作的版本,但我想减less我的代码,所以我没有一个漫长而笨拙的子。 我确信有一种方法可以让它在For Each Cell循环中工作,但是对于我来说,我无法弄清楚它是如何工作的。 我可以使用vlookup来解决这个问题,但是我相信当查看大范围的数据时,索引/匹配是一个更好的解决scheme(我的命名表超过了10k行)
以下是我的实际工作,但有点长:
Range("C38:F38").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[NAME],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") Range("C39:F39").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[infodyn_DELIVERY_ADDRESS.ADDRESS_1],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") Range("C40:F40").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[infodyn_DELIVERY_ADDRESS.ADDRESS_2],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") Range("C41:F41").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[infodyn_DELIVERY_ADDRESS.ADDRESS_3],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") Range("C42:F42").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[infodyn_DELIVERY_ADDRESS.TOWN],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") Range("C43:F43").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[infodyn_DELIVERY_ADDRESS.COUNTY],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") Range("C44:F44").Select Selection.MergeCells = True Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA[infodyn_DELIVERY_ADDRESS.POST_CODE],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")")
在这里我已经想出了如何应用循环来处理合并部分,但我很难在每个实例中如何进行索引/匹配更改索引的列标题:
For Each Cell In Range("C38:C44").Cells Cell.Resize(, 4).Select Selection.Merge 'Something in here with the Index/Match Formula changing the Column Header on each turn through the loop Next Cell
任何想法或build议非常感激。
您可以为列名设置一个数组,并在循环中连接它们。 你只需要跟踪列。
Dim columnNames(6) As String Dim i as Integer i=0 columnNames(0) = "NAME" 'Rest of columns. columnNames(6) = "infodyn_DELIVERY_ADDRESS.POST_CODE" 'Inside loop Selection.Formula = ("=IFERROR(INDEX(MAIN_DATA["& columnNames(i) &"],MATCH($D$10,MAIN_DATA[PURCHASE_ORDER_ID],FALSE),0),"""")") i = i +1