如何编写VBA根据可用行而不是整列进行索引和匹配?

问题描述 投票:0回答:1
Sub ApplyFormulas()
Dim ws As Worksheet
Dim lastRow As Long
Dim newCol As Long

Set ws = ThisWorkbook.Sheets("Sheet1") 

lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

newCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column + 1
ws.Cells(1, newCol).Value = "Formula"

ws.Range(ws.Cells(2, newCol), ws.Cells(lastRow, newCol)).Formula2 = "=INDEX(Sheet2!E:E, MATCH(1, (Sheet2!A:A=Sheet1!A2)*(Sheet2!C:C=Sheet1!C2), 0))" 

如何更改公式

=INDEX(Sheet2!E:E,

=INDEX(Sheet2!$E$2:$E$54483

搜索数组是固定的,并且基于 Sheet2 中的可用行,因为我将对不同的文件使用相同的宏

excel vba
1个回答
0
投票
  • 该方法类似于如何获取 Sheet1 A 列中的最后一行号。
    Dim lastRowE As Long, ws2 As Worksheet
    Set ws2 = ThisWorkbook.Sheets("Sheet2")
    lastRowE = ws2.Cells(ws2.Rows.Count, "E").End(xlUp).Row
    ws.Range(ws.Cells(2, newCol), ws.Cells(lastRow, newCol)).Formula2 = "=INDEX(Sheet2!E2:E" & lastRowE & ", MATCH(1, (Sheet2!A2:A" & lastRowE & "=Sheet1!A2)*(Sheet2!C2:C" & lastRowE & "=Sheet1!C2), 0))"
© www.soinside.com 2019 - 2024. All rights reserved.