VBAvalidation正在崩溃我的工作簿

我有VBA代码来改变依赖于所选选项的单元格validation。

Sub Worksheet_Change(ByVal Target As Range) Dim ws As Worksheet Set ws = Sheets("lkup") Dim VariationList As Variant VariationList = Application.Transpose(ws.Range("Resource_List")) For i = LBound(VariationList) To UBound(VariationList) Next i If Target = Range("B15") Then If InStr(1, Range("B15"), "Resource") > 0 Then With Range("D15").Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ Operator:=xlEqual, Formula1:=Join(VariationList, ",") .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With ElseIf InStr(1, Range("B15"), "Fixed Asset") > 0 Then Range("D15").Validation.Delete Range("D15").ClearContents With Range("D15").Validation .Delete .Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertStop, _ Operator:=xlBetween, Formula1:="100000", Formula2:="999999" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "Oopps" .InputMessage = "" .ErrorMessage = "Your fixed asset number can only be 6 numbers" .ShowInput = True .ShowError = True End With Else Range("D15").ClearContents Range("D15").Validation.Delete End If End If End Sub 

它在工作簿打开时工作。 它运行良好,没有错误或任何东西。 但是,当我保存并重新打开工作簿时,它给了我以下内容:

我们发现“Invoice.xlsm”中的某些内容存在问题。 你想让我们尽可能地恢复吗? 如果您信任此工作簿的来源,请单击“是”。

然后打开工作簿,去掉所有的格式并删除VBA。

我试过谷歌search,但一直没有能够翻译到我有什么。

干杯,

在使用Worksheet_Change更改ActiveSheet上的值之前,需要closures事件。 这可以防止再次触发Worksheet_Change并可能导致无限循环。 确保在事件退出之前将其重新打开。

添加一个error handling程序是一个很好的习惯,所以如果事情出错了,事件会自动重新开启。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) On Error GoTo ResumeEvents Application.EnableEvents = False '----{Code}------ ResumeEvents: Application.EnableEvents = True End Sub