【发布时间】:2019-12-24 10:40:30
【问题描述】:
最初我不知道为什么我的 Excel 文件不断损坏,但经过大量研究后,我意识到这是因为我的数据验证下拉列表有超过 255 个字符。 “超过 255 个字符(包括逗号)的逗号分隔数据验证列表将损坏工作簿”
这是我的代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("E12:E21")) Is Nothing Then
Dim col As New Collection
Dim rng As Range
Dim i As Long
Dim dvlist As String
'Loop thru the data range i.e. these are the cells used for the validation list. Very long list.
For Each rng In Sheet2.Range("B2:B249 , D2:D19")
'ignore blanks
If Len(Trim(rng.Value)) <> 0 Then
'create a unique list
On Error Resume Next
col.Add rng.Value, CStr(rng.Value)
On Error GoTo 0
End If
Next rng
'concatenate with "," as the delimiter
For i = 1 To col.Count
dvlist = dvlist & col.Item(i) & ","
Next i
'add it to the DV
With Sheet1.Range("E12:E21").Validation
.Delete
.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=dvlist
End With
End If
If Not Intersect(Target, Range("F12:F21")) Is Nothing Then
'Loop thru the data range i.e. these are the cells used for the validation list. Very long list.
For Each rng In Sheet2.Range("A2:A249")
'ignore blanks
If Len(Trim(rng.Value)) <> 0 Then
'create a unique list
On Error Resume Next
col.Add rng.Value, CStr(rng.Value)
On Error GoTo 0
End If
Next rng
'concatenate with "," as the delimiter
For i = 1 To col.Count
dvlist1 = dvlist1 & col.Item(i) & ","
Next i
'add it to the DV
With Sheet1.Range("F12:F21").Validation
.Delete
.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=dvlist1
End With
End If
End Sub
如您所见,我的列表很长,并且列表之间有空格,由于某些原因,无法删除。因此,我无法在 Excel 中使用数据验证功能。有什么办法可以解决这个问题吗?
【问题讨论】:
-
也许您可以在工作表上的范围内打印该范围并将该范围设置为验证范围。另外,如果您能就您之前的问题提供反馈,那就太好了:)
-
嘿@Mikku,嗯..但是范围已经是验证列表。而且我知道ww ..,很抱歉,因为我仍在对其进行测试,所以我不想在另一个线程中对您的回答做出轻率的回应。确认代码后我会回复!我的道歉
-
目前我不确定由于此错误代码是否真的有效
-
是的,应该可以。
-
@Mikku 我做了那个 Mikku!谢谢
标签: excel vba error-handling dropdown