2012-11-19 109 views
0
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 

由於某種原因,我的查找功能不起作用。我嘗試了幾種方法,並且陷入困境。任何人都可以提供任何幫助Excel 2010 VBA查找功能問題

+0

我看到'for',而不是'next'?這是一個錯字,還是你真的面臨一些錯誤? – Passerby

+0

接下來我只是無法適應所有的代碼。我沒有得到一個錯誤,但我得到#Value在單元格中返回 – user1667541

+0

你沒有從你的函數返回任何值。某處應該有一行'ProtectiveDiscount = [whateverValueYouCalculated]'你有第二次查找使用該函數的PDD參數而其他人不這樣做的原因嗎? –

回答

0

我真的沒有看到使用一個if ...結束點,如果x4和不使用If ... elseif ... elseif ...結束如果。但即使這可能不需要,因爲if內的動作是相同的......也許你應該考慮if(a = a1)或(a = a2)或... Then ... 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數組)。

乾杯

+0

通過單元格迭代很少比內置函數更快。 – Brad