2015-10-14 204 views
0

我有我的宏的問題。我知道它的很多代碼(爲此),但我認爲它可以是有幫助的。所以我想要做的基本事情是,取出組合框的值並在另一個工作表中搜索它,以便將價格寫入下一列。 到目前爲止,但在im搜索的名稱是不唯一的數據庫中。一個IM搜索僅由beeing正確的命名範圍內的部分定義(即EngineMercedesDiesel)Excel VBA命名範圍與動態創建名稱

Function getprice(Matrix As Range, name As String) 

Dim i As Integer 
Dim row As Variant 
Dim col As Variant 
Dim price As Variant 
'loop to finde inside the range the name im looking for 
For i = 1 To Matrix.Rows.Count 
    If Matrix.Cells(i, 1).Value = name Then 
     row = Matrix.Cells(i, 1).Address(RowAbsolute:=True) 
     col = Matrix.Cells(i, 1).Address(ColumnAbsolute:=True) 
     price = Tabelle2.Cells(row, col + 1).Value 
     Exit For 
Next 

getprice = price 

End Function 

Private Sub cbschaltung_Change() 

Dim go As Range 
Dim handle As String 

'from here it builds the name i.e. EngineMercedesDiesel an there is a Named range with the same titel outside VBA 

teil = Range("A4").Value 
hersteller = Range("B3").Value 
handle = cbschaltung.Value 

If checkboxel.Value = True Then 

    c = checkboxel.Caption 
    Set go = teil & hersteller & c 'storing to the variable go, here ocures the error 
    Tabelle3.Range("C4").Value = getprice(go, handle) 

ElseIf checkboxmech.Value = True Then 

    c = checkboxmech.Caption 
    Set go = teil & hersteller & c 
    Tabelle3.Range("C4").Value = getprice(go, handle) 

End If 

End Sub 

我希望你們能幫助我,(希望)你對我有一個簡單的答案

+1

你可以傳遞正確的命名範圍作爲函數的另一個參數嗎?如果是這樣,我認爲在這種情況下代碼很容易更新。 –

+0

sry我不明白你的意思是「另一個論點」! 問題是,即使我直接輸入名稱到函數中也不起作用,因爲他有些不知道它是一個範圍 – Quantum

+0

我看到你得到了你的答案,但我所建議的是通過命名範圍到修復。因此,不是隻使用'Matrix'和'name'中的兩個參數,而是爲命名範圍添加第三個參數。無論哪種方式,你有你需要的東西:) –

回答

0

確定我終於做到了!

ElseIf checkboxmech.Value = True Then 

    c = checkboxmech.Caption 
    mname = teil & hersteller & c 
    Set go = Worksheets("Gruppendatenbank").Range(mname) 
    Tabelle3.Range("C4").Value = getprice(go, handle) 

將mname定義爲變體數據類型並定義我的範圍的工作表是非常重要的。 感謝您的幫助

statusupdate:求解!