使用仅包含字符串,没有地址的命名范围的数据验证

时间:2018-01-28 22:53:34

标签: excel vba excel-vba

我正在为一群不那么舒服的excel用户创建一个工作簿/跟踪器,因此我已经命名了所有范围,如下面链接的图片所示(抱歉,我没有足够的代表将它放入我的后)。它们的范围是工作簿。

我给了他们一个名字,即“TEST”& “TESTMEMBERS”并在UI中手动填充其内容( Ctrl F3 ),以便用户可以根据需要轻松修改命名范围。它们的内容只是一个字符串,而不是指工作簿中某处的一系列单元格。

例如:

  

“TESTMEMBERS”具有以下数据(也称为):=“Member1,Member2”

我的问题是如何从命名区域获取数据以用于使用VBA对单元格进行数据验证?

我在设置regOffice 的行中收到以下错误:

  

运行时错误'1004'   对象'_Worksheet'的方法'Range'失败

以下是我的代码中存在问题的部分。值得注意的是,sub是 Worksheet_Change 。如果您需要更多,请告诉我。我很乐意发布它。我已经包含了DIM部分,以确保我按照预期设置了所有内容。

Dim regOffice As Range 'Range which will contain all the regional offices Dim hearingLoc As Range 'Range which will contain the hearingLoc specific to the Reg Office Dim wsTracker As Worksheet 'Worksheet var which will ref the Tracker Worksheet Dim colCounter As Long 'Counter Dim i As Long Dim hearingDates As Range Dim day As Range Dim tableHeaders As Range Dim header As Range Dim colLoc As Long Dim colOpened As Long Dim colScheduled As Long Dim colRecording As Long Dim colAdjourned As Long Dim foundLocation As Range Set wsTracker = Application.ActiveSheet Set regOffice = Range("TEST") 'The purpose here is to use regOffice range later and iterate through it's values. 'Office Location Validation With Range("B24", "B100").Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Formula1:="=TEST" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = False End With 'Member Name Validation With Range("D24", "D100").Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Formula1:="=TESTMEMBERS" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = False End With

Picture of how the Named Range is set-up

2 个答案:

答案 0 :(得分:1)

范围必须参考单元格。您创建了一个不引用单元格的名称,当您尝试将其分配给RegOffice时,您会收到错误。这就解释了为什么你会收到错误。像

这样的东西
 ThisWorkbook.Names("TEST").RefersTo 

也许可以帮助您访问所需的信息,但我建议将所有成员放在单元格中,然后创建引用这些单元格的名称“TEST”。你的方式,你的代码应该工作

答案 1 :(得分:0)

回答我自己的问题:(对不起,如果这不正确,认为在遇到类似问题时让其他人知道是好事。)

经过一番研究,并发布到处都是。确定这是一个NAME而不是RANGE。

我不得不重新编写一些代码并更改内容以使其工作使用数组和拆分函数以使用for循环遍历数组。

关于我发布的代码,这里已修复,但我只保留了声明部分发生变化的内容。

conda