请帮我创建具有excel IF,索引,匹配功能的VBA功能。这是我的excel功能:
=IF(INDEX(Grid!$B$3:$G$6,MATCH('Sal-Data'!$A2,Grid!$A$3:$A$6,0),MATCH('Sal-Data'!$B2+1,Grid!$B$2:$G$2,0))=0,$B2,$B2+1)
我在这里添加了VBA代码,但这不起作用,我想从Grid Sheet获得下一级别的结果。例如,如果当前网格在Sheet" Sal-data"对于Emp" b"是2然后新的Grid将是3,但是" Grid"表" b"网格3为0(零),然后网格不应该增加。在这种情况下,如果" b"当前网格是3然后b的下一个网格可能得到4,但网格4的值是0然后" b" s网格不应该因为没有值而增加。
这是我的VBA编码:
Public Function NGrid(rData As Range, rBudCode As Range, rMo As Range, budgetcode As Variant, mo As Variant)
Dim rw As Variant
Dim col As Variant
With Application
col = .Match(budgetcode+1, rBudCode, 0)
rw = .Match(mo, rMo, 0)
NGrid = .Index(rData, col, rw)
If NGrid= 0 Then
With Application
col = .Match(budgetcode, rBudCode, 0)
rw = .Match(mo, rMo, 0)
NGrid = .Index(rData, col, rw)
Else
With Application
col = .Match(budgetcode+1, rBudCode, 0)
rw = .Match(mo, rMo, 0)
NGrid = .Index(rData, col, rw)
End if
End with
End Function
Excel sheet name : Grid
1 2 3 4 5 6
a 10 11 12 13 0 0
b 20 21 22 0 0 0
c 30 31 32 33 34 0
d 40 41 42 0 0 0
Excel sheet name : Sal-Data
Emp grid New grid
a 4 = NGrid (...) required VBA function
a 2
b 1
b 2
比你提前。
答案 0 :(得分:0)
一,你不需要Else,因为它只是重复了第一个。
两个,每个With
需要End With
,在这种情况下,不需要其他With Application
。
三,索引为Row,Column
而非Column,Row
Public Function NGrid(rData As Range, rBudCode As Range, rMo As Range, budgetcode As Variant, mo As Variant)
Dim rw As Long
Dim col As Long
With Application
col = .Match(budgetcode + 1, rBudCode, 0)
rw = .Match(mo, rMo, 0)
NGrid = .Index(rData, rw, col)
If NGrid = 0 Then
col = .Match(budgetcode, rBudCode, 0)
rw = .Match(mo, rMo, 0)
NGrid = .Index(rData, rw, col)
End If
End With
End Function
然后确保在rData:
中包含标题行和列=NGrid(Grid!$A$1:$G$5,Grid!$A$1:$G$1,Grid!$A$1:$A$5,B2,A2)
这允许仅使用网格范围,无需以不同方式指定第一行和第一行:
Public Function NGrid(rData As Range, budgetcode As Variant, mo As Variant)
Dim rw As Long
Dim col As Long
Dim rBudCode As Range
Dim rMo As Range
With Application
Set rBudCode = rData.Rows(1)
Set rMo = rData.Columns(1)
col = .Match(budgetcode + 1, rBudCode, 0)
rw = .Match(mo, rMo, 0)
NGrid = .Index(rData, rw, col)
If NGrid = 0 Then
NGrid = .Index(rData, rw, col - 1)
End If
End With
End Function
所以上面的公式是:
=NGrid(Grid!$A$1:$G$5,B2,A2)
网格表:供参考
答案 1 :(得分:0)
未测试:
Public Function NGrid(rData As Range, rBudCode As Range, rMo As Range, budgetcode As Variant, mo As Variant)
Dim rw As Variant, col As Variant
With Application
col = .Match(budgetcode + 1, rBudCode, 0)
rw = .Match(mo, rMo, 0)
If Not IsError(rw) Then
If Not IsError(col) Then
NGrid = .Index(rData, col, rw)
If NGrid = 0 Then
col = .Match(budgetcode, rBudCode, 0)
If Not IsError(col) Then
NGrid = .Index(rData, col, rw)
Else
NGrid = "budget?" 'no col match
End If
End If
Else
NGrid = "budget+1?" 'no col match on +1
End If
Else
NGrid = "mo?" 'no row match
End If
End With
End Function
如果您的源数据始终在第一列和第一行中有查找,那么您实际上只需要传入一个范围:您可以使用.Rows(1)
和.Columns(1)
从中选择查找范围