Excel 2010 VBA查找功能问题

时间:2012-11-19 02:24:10

标签: excel-vba vba excel

Function ProtectiveDiscount(PDD As Range)
'‘Find discount in table
TotalDiscount = 0
For i = 0 To ListBox1.ListCount - 1

If ListBox1.Selected(i).Value = "Dead bolt, Local Fire Alarm, Fire extinguisher" Then
Msg = Msg & ListBox1.List(i) & vbNewLine
TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Worksheets("Sheet4").Range("PDD"), 2, False)
' TotalDiscount = TotalDiscount +  WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Range("R50:S55"), 2, False)
End If

If ListBox1.Selected(i).Value = "Burglar Alarm with Reporting" Then
Msg = Msg & ListBox1.List(i) & vbNewLine
TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, PDD, 2, False)
' TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Range("R50:S55"), 2, False)
End If

If ListBox1.Selected(i).Value = "Fire Alarm with Reporting" Then
Msg = Msg & ListBox1.List(i) & vbNewLine
TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Worksheets("Sheet4").Range("PDD"), 2, False)
 'TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Range("R50:S55"), 2, False)
End If

If ListBox1.Selected(i).Value = "Automatic Sprinkler in all areas" Then
Msg = Msg & ListBox1.List(i) & vbNewLine
TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Worksheets("Sheet4").Range("PDD"), 2, False)
' TotalDiscount = TotalDiscount + WorksheetFunction.VLookup(ListBox1.Selected(i).Value, Range("R50:S55"), 2, False)
End If
End Function

由于某种原因,我的vlookup功能不起作用。我尝试了几种方法而且卡住了。任何人都可以提供任何帮助

1 个答案:

答案 0 :(得分:0)

我真的没有看到使用if ...结束如果x4并且不使用If ... elseif ... elseif ... end if if。但即使这可能也不需要,因为Ifs中的动作是相同的...也许你应该考虑if(a = a1)或(a = a2)或......然后...... elseif ...... else ...如果形式结束。无论如何,既然你可能只发布了部分代码,我就此没有进一步说明。关于Vlookup部分,我相信这种形式:

If ListBox1.Selected(i).Value="Dead bolt, Local Fire Alarm, Fire extinguisher" Then
    Msg = Msg & ListBox1.List(i) & vbNewLine
    TotalDiscount = TotalDiscount + application.WorksheetFunction.VLookup(ListBox1.Selected(i).Value, PDD, 2, False) 
elseif ListBox1.Selected(i).Value = "Burglar Alarm with Reporting" Then

应该可以正常工作。

也是一个小评论。尽管使用工作表函数更容易/更快地编写,但是使用Cells()在VBA内搜索并使用for-next循环在指定范围内查找可能会更快,尤其是因为您不使用Fast Vlookup(已排序)数组)。

干杯