2012-10-16 46 views
1

我試着填補組合框時(拖動到我的工作表),其動態範圍的值。Excel的VBA錯誤使用動態範圍

Normaly'ThisWorkbook.Names( 「NAME_OF_RANGE」)。RefersToRange的作品,但它在我的動態範圍,失敗!

我已經嘗試了不同的解決方案(見下面的代碼),但隨後的worksheetname從參考剝離(因此錯誤的數據填充)

Public Sub FillCombobox(cboComboBox As ComboBox, sRange As String) 
'Remember current selected item 
Dim sSelectedItem As String 
sSelectedItem = cboComboBox.Text 

'Empty the combobox 
cboComboBox.Clear 
cboComboBox.AddItem "---pick one---" 

'Get the data from the dynamic range 
Dim oListFillRange As Range 
'This line will throw an error: 
Set oListFillRange = ThisWorkbook.Names(sRange).RefersToRange 'Does not work with a dynamic range!!! 
''Set oListFillRange = Range(Application.Evaluate(ThisWorkbook.Names(sRange).RefersTo).Address) 'Works with dynamic ranges on the SAME SHEET (as the sheetname is stripped out!) 

'Fill combobox 
Dim oRange As Range 
For Each oRange In oListFillRange 
    cboComboBox.AddItem oRange.Value 
Next oRange 

'Set previous selected item 
Dim i As Integer 
For i = 0 To cboComboBox.ListCount - 1 
    If cboComboBox.List(i) = sSelectedItem Then 
     cboComboBox.ListIndex = i 
     Exit for 
    End If 
Next i 

If cboComboBox.ListIndex = -1 Then cboComboBox.ListIndex = 0 
End Sub 

那麼,如何讓「的ThisWorkbook。名稱(「NAME_OF_RANGE」)。RefersToRange'使用動態範圍?

回答

1

參考範圍由Range財產。

Set oListFillRange = Sheets("mySheet").Range(sRange) 'where mySheet is the relevant sheet name 

對於一些更多的信息,即RefersToRange不工作的原因是,因爲在公式用於動態範圍中沒有範圍,所以高強屬性不能讀取的實際範圍。因此,直接參考範圍是唯一的出路。

+0

您的加入表名稱建議的工作,謝謝!我寧願用「global'method,所以當我重命名錶,我不擔心我的更新VBA代碼,但好像我在這裏沒有選擇... –

+0

是的,現在我想它,無論如何你都需要表單名稱。我會編輯我的答案以更準確。 –

+0

我可以使用Name.RefersToRange引用動態範圍。但你的答案更直接。 –