2015-09-30 71 views
0

我在寫一個代碼嵌入到一個表中。情況如下: 單元格A1(選項爲50,100和150)和單元格A2(選項爲1000和5000)都包含數據驗證列表。當我選擇的50單元格A1,A2必須是1000。當我寫的代碼和作出的選擇,總有一個錯誤:VBA數據驗證列表選擇

Run-time error '-2147417848(80010108)': Method 'Add' of object 'Validation' failed.

請分享您的意見,或者如果需要我在這裏發佈我的代碼解決這個問題。

的基本代碼如下:

Select Case Range("A1").Value 
Case "50" 
     Range("A2").ClearContents 
     Range("A6").Value2 = "1000" 

Case "`100" 
     Range("A2").ClearContents 
     With Range("A2").Validation 
     .Delete 
     .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _ 
     :=xlBetween 
     .IgnoreBlank = True 
     .InCellDropdown = True 
     .InputTitle = "" 
     .ErrorTitle = "" 
     .InputMessage = "" 
     .ErrorMessage = "" 
     .ShowInput = True 
     .ShowError = True 
    End With 
     Range("A2").Value2 = 1000 
+0

歡迎堆棧溢出。你需要提供更多信息。如何發佈你寫的代碼。 – HarveyFrench

+0

以下是代碼:選擇範圍(「A1」)。值例50,範圍(「A2」)。值= 1000結束選擇我認爲它應該是一個簡單的代碼,但在Excel工作簿中,當我選擇50在A1中,出現錯誤,我的excel崩潰了, –

+0

您是否知道調試VBA代碼的問題。如果沒有發現。你需要引用給你的錯誤。你的代碼是否被編譯?你的代碼是什麼模塊。 – HarveyFrench

回答

0

這個代碼添加到片材所需的單元格的模塊驗證添加到

Private Sub Worksheet_Change(ByVal Target As Range) 

    If Target.Address = "$A$1" Then 

     If Target.Value = 50 Then 

      Range("A2") = 1000 

      ' Add valid values of 1000 allowed only 
      With Range("A2").Validation 
       .Delete 
       .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="1000" 
       .IgnoreBlank = True 
       .InCellDropdown = True 
       .InputTitle = "" 
       .ErrorTitle = "" 
       .InputMessage = "" 
       .ErrorMessage = "Enter a valid value" 
       .ShowInput = False 
       .ShowError = True 
      End With 

     Else 
      ' Add valid values of 1000 and 5000 allowed 
      With Range("A2").Validation 
       .Delete 
       .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="1000,5000" 
       .IgnoreBlank = True 
       .InCellDropdown = True 
       .InputTitle = "" 
       .ErrorTitle = "" 
       .InputMessage = "" 
       .ErrorMessage = "Enter a valid value" 
       .ShowInput = False 
       .ShowError = True 
      End With 
     End If 




    End If 

End Sub 
+0

嗨,朋友。它確實有用!非常感謝!但是你知道我錯了哪一部分嗎?你的代碼非常有用,但對於這部分「如果Target.Address =」$ A $ 1「那麼」A1「和」$ A $ 1「之間有什麼區別。你能爲我解釋一下嗎?再次感謝, –