简体   繁体   English

使用动态范围时Excel VBA错误

[英]Excel VBA error when using dynamic ranges

I am tryin to fill a combobox (dragged onto my worksheet) with the values of a dynamic range. 我正在尝试用动态范围的值填充组合框(拖到我的工作表上)。

Normaly 'ThisWorkbook.Names("NAME_OF_RANGE").RefersToRange' works, but it fails on my dynamic range! 通常,“ ThisWorkbook.Names(“ NAME_OF_RANGE”)。RefersToRange'可以正常工作,但是在我的动态范围上失败了!

I have tried a different solution (see code below), but then the worksheetname is stripped from the reference (and thus the wrong data is being filled) 我尝试了一种不同的解决方案(请参见下面的代码),但是随后将工作表名称从引用中剥离了(从而填充了错误的数据)

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

So how do I get 'ThisWorkbook.Names("NAME_OF_RANGE").RefersToRange' to work with dynamic ranges? 那么,如何获取'ThisWorkbook.Names(“ NAME_OF_RANGE”)。RefersToRange'以使用动态范围?

Refer to the range by the Range property. 通过Range属性引用Range

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

For some more information, the reason that RefersToRange does not work is because there is no range in the formula for dynamic ranges, so the excel properties cannot read the actual range. 有关更多信息, RefersToRange不起作用的原因是因为公式中没有动态范围的范围,因此excel属性无法读取实际范围。 Therefore, referring to the range directly is the only way to go. 因此,直接引用范围是唯一的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM