如何通过VBA代码添加验证列表,该列表将引用另一个CLOSED工作簿范围?我不能Formula1:="=INDEX('C:\...)"
吗?
我可以管理:
With ThisWorkbook.Sheets("sertifika").Range("Ab63:Ab100").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop,
Operator:=xlBetween, _
Formula1:=Join(checkref, ",")
但是对于长字符串值,files.xlsm文件在保存后会损坏。
然后我尝试:
With ThisWorkbook.Sheets("T").Range("K10:K100").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop,
Operator:=xlBetween, _
Formula1:="=INDEX('C:\[D.xls]Lists'!$D$2:$D$10,,1)"
Return error 1004
答案 0 :(得分:0)
根据Microsoft的文档,您不能在数据验证中使用外部引用。您可以在以下链接中找到文档...
https://docs.microsoft.com/en-us/office/troubleshoot/excel/external-references-data-validation-fails
作为一种解决方法,可以使用ExecuteExcel4Macro方法来访问封闭工作簿中的值。您可以在以下链接中找到文档...
https://docs.microsoft.com/en-us/office/vba/api/excel.application.executeexcel4macro
使用此方法,将访问值以构建字符串,然后将其用作验证的源。 请注意,但是字符数不能超过255个。
此外,这意味着您每次打开工作簿时都需要更新数据验证,以确保您拥有最新的值。为此,可以使用工作簿打开事件过程。
解决方法
[常规模块]
以下宏应放在常规模块中,并将添加来自外部源的数据验证...
Option Explicit
Sub UpdateDataValidation()
Dim sourcePath As String
sourcePath = "C:\Users\Domenic\Desktop\" 'change the path accordingly
Dim sourceFileName As String
sourceFileName = "Sample.xlsm" 'change the file name accordingly
Dim sourceSheetName As String
sourceSheetName = "Sheet1" 'change the sheet name accordingly
Dim sourceReference As String
sourceReference = "D2:D10" 'change the reference accordingly
Dim currentCell As Range
Dim currentValue As String
Dim validationList As String
validationList = ""
For Each currentCell In Worksheets(1).Range(sourceReference) 'any worksheet reference will do for our purposes here
currentValue = ExecuteExcel4Macro("'" & sourcePath & "[" & sourceFileName & "]" & sourceSheetName & "'!" & currentCell.Address(, , xlR1C1))
validationList = validationList & "," & currentValue
Next currentCell
validationList = Mid(validationList, 2)
With ThisWorkbook.Sheets("Sheet1").Range("A10:A100").Validation 'change the sheet name and range accordingly
.Delete
.Add _
Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=validationList
End With
End Sub
[ThisWorkbook模块]
以下宏应放置在ThisWorkbook的代码模块中,并在每次打开工作簿时自动更新用于数据验证的值...
Option Explicit
Private Sub Workbook_Open()
UpdateDataValidation
End Sub