【发布时间】:2020-09-08 07:03:10
【问题描述】:
下午好,
我想让我的列表自动更新工作,但我不知道该怎么做。
您可以在上面看到的列表是我的测试列表。右侧有组合框,我在其中设置了属性: 链接列为 R2 单元格范围为:A2:A6。
它工作正常,您可以在右侧下拉菜单中看到。单元格区域 A2:A6 中的记录已正确填充。
问题是,该列表将被开发,因为新数据将逐行出现。在这种情况下,我无法保持这个范围固定。
我尝试使用此处提供的代码对其进行管理:
dropdown list with autocomplete/ suggestion in excel vba
到目前为止,我的代码如下所示:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim vType As XlDVType
On Error GoTo EndLine
vType = Target.Validation.Type
Dim xCombox As OLEObject
Dim xStr As String
Dim xWs As Worksheet
Dim Cancel As Boolean
Set xWs = Application.ActiveSheet
'On Error Resume Next
Set xCombox = xWs.OLEObjects("Combobox1")
With xCombox
Dim OrigRange As Range: OrigRange = .ListFillRange
If Not Application.Intersect(OrigRange, Target) Is Nothing Then
.ListFillRange = .OrigRange.Resize(OrigRange.Cells(1).End(xlDown).Row - OrigRange.Row + 1)
End If
'.ListFillRange = .OrigRange.Resize(OrigRange.Cells(1).End(xlDown).Row - OrigRange.Row + 1)
.LinkedCell = "=A"
.Visible = False
End With
If vType = 3 Then
Target.Validation.InCellDropdown = False
Cancel = True
xStr = Target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
If xStr = "" Then Exit Sub
With xCombox
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 5
.Height = Target.Height + 5
.ListFillRange = xStr
.LinkedCell = Target.Address
End With
xCombox.Activate
Me.ComboBox1.DropDown
End If
EndLine:
End Sub
代码与自动填充一起使用,很好。但是我不得不混合一些东西,因为我现在看不到任何反应。代码有效并且自动填充是正确的,但自动更新不起作用。我将新值放在下面,超出了属性中的固定单元格范围,它们不会出现在下拉列表中,您可以看到。
有什么办法让它运行吗?
更新:
最近解决问题的方法:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim vType As XlDVType
On Error GoTo EndLine
vType = Target.Validation.Type
Dim xCombox As OLEObject
Dim xStr As String
Dim xWs As Worksheet
Dim Cancel As Boolean
Set xWs = Application.ActiveSheet
'On Error Resume Next
Set xCombox = xWs.OLEObjects("Combobox1")
With xCombox
Dim OrigRange As Range: Set OrigRange = xWs.Range("A2:A" & xWs.Range("A" & xWs.Rows.Count).End(xlUp).Row)
If Not Application.Intersect(OrigRange, Target) Is Nothing Then
.ListFillRange = OrigRange.Address
End If
.LinkedCell = "R2" '??
.Visible = True 'Dont know why hide ??
End With
If vType = 3 Then
Target.Validation.InCellDropdown = False
Cancel = True
xStr = Target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
If xStr = "" Then Exit Sub
With xCombox
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 5
.Height = Target.Height + 5
.ListFillRange = xStr
.LinkedCell = Target.Address
End With
xCombox.Activate
Me.ComboBox1.DropDown
End If
EndLine:
End Sub
删除 ListFillRange 属性后,组合框下拉列表完全空白。
【问题讨论】: