VBA索引/匹配空白单元格

时间:2017-02-07 07:17:25

标签: vba indexing match

我有一个帐户清单&代码,并希望使用索引匹配来填充来自不同工作表的结果的列。我可以使用以下公式使其工作:= index(rngB,match(BCode,rngM,0),55)

但无法将其翻译为vba。我试过了:

sub compare() 

Dim BudgetResult As Long
Dim var1 As Long
Dim rngB, rngM As Range
Dim CompSH, ActSH, BudSH As Worksheet
Dim BCode As Variant

Set CompSH = Sheets.Add(After:=Sheets(Sheets.Count))
Set ActSH = Sheets(2)
Set BudSH = Sheets(3)
Set rngB = BudSH.Range("B11:BF50")
Set rngM = BudSH.Range("B:B")
Set BCode = CompSH.Range("A2")

BudSH.Select
Range("B10:E76").Select
Selection.Copy
CompSH.Select
ActiveSheet.Paste
Range("F1").Select
ActiveCell.FormulaR1C1 = "Budget"
Range("F2").Select

With Application.WorksheetFunction

var1 = .Match(BCode, rngM, 0)
BudgetResult = .Index(rngB, var1, 55)

End With

我得到一个空白单元格。没有结果表。 另外,我不知道如何继续下去。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

你可能会追随以下内容

Option Explicit

Sub compare()
    Dim rngB As Range, rngM As Range, cell As Range
    Dim CompSH As Worksheet, ActSH As Worksheet, BudSH As Worksheet
    Dim AW As WorksheetFunction: Set AW = Application.WorksheetFunction

    Set CompSH = Sheets.Add(After:=Sheets(Sheets.count))
    Set ActSH = Sheets("ActSH") 'Sheets(2)
    Set BudSH = Sheets("BudSH") 'Sheets(3)

    With BudSH
        Set rngB = .Range("B11:BF50") '<--| warning: your "index" range has 40 rows
        Set rngM = .Range("B:B")
        .Range("F1").Value = "Budget"
        .Range("B10:E76").Copy CompSH.Range("A1") '<--| warning: your "copied" range has 67 rows
    End With

    With CompSH
        For Each cell In .Range("A2", .Cells(.Rows.count, 1).End(xlUp))
            cell.Offset(, 5).Value = AW.Index(rngB, AW.Match(cell, rngM, 0), 55) '<--| this will error when trying to access from 'rngB' range 41th rows on
        Next
    End With
End Sub

您只需在标有<--| Warning...

的对帐单中调整范围大小