使用dynamic范围时出现Excel VBA错误

我试着用dynamic范围的值填充combobox(拖动到我的工作表上)。

正常'ThisWorkbook.Names(“NAME_OF_RANGE”)。RefersToRange“的作品,但它失败了我的dynamic范围!

我已经尝试了一个不同的解决scheme(请参阅下面的代码),但是工作表名称被从参考中剥离(因此错误的数据被填充)

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.Names(“NAME_OF_RANGE”)。RefersToRange'来处理dynamic范围?

通过Range属性来引用Range

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

有关更多信息, RefersToRange不起作用的原因是因为在dynamic范围的公式中没有范围,所以excel属性无法读取实际范围。 因此,直接参考范围是唯一的方法。