2016-06-13 170 views
0

我正在嘗試爲單元指定驗證列表。例如,如果單元格「C6」的值爲28,則驗證列表是可變的,例如,如果單元格「C6」的值是28,則驗證列表應該是範圍Sheet4.Range(「b4:b20」)。正如你所看到的驗證列表是從另一個sheet.in爲了做到這一點,我寫了下面的代碼使用VBA進行單元驗證

ValrStart = Sheet4.Cells(rowno, 4).Address ‘rowno is the row in which the validation list starts and its value comes from another part of the code 
ValrEnd = Sheet4.Cells(rownoEnd, 4).Address rownoEnd is the row in which the validation list ends and its value comes from another part of the code 
Rng = "Sheet4.Range(""" & ValrStart & Chr(58) & ValrEnd & """" & ")" 
With Cells(20, 3).Validation 
      .Delete 
      .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ 
      Operator:=xlBetween, Formula1:=Rng 
      .ErrorMessage = "Invalid value. Select one from the dropdown list." 
      check = Cells(20, 3).Validation.Value 
      If check = False Then 
      Cells(20, 3).ClearContents 
      Exit Sub 
      End If 
     End With 

現在發生的是什麼我出現在Cell是字符串RNG的值不它代表的範圍。 任何人都可以幫忙嗎? 感謝

回答

1

的問題是在Formula1參數,它必須有一個「=」在其開始

我不得不Excel中完成這個艱難的工作,爲你喜歡的如下:

Dim rng As Range '<~~ set rng as of a Range type 
With Sheet4 
    Set rng = .Range(.Cells(rowno, 4), .Cells(rownoEnd, 4)) '<~~ set rng to the wanted range 
End With 

With Cells(20, 13).Validation 
    .Delete 

    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _ 
    Operator:=xlBetween, Formula1:="=" & rng.Address(, , , True) '<~~ have Address function take out the correct formula, just add a "=" at the beginning 

    .ErrorMessage = "Invalid value. Select one from the dropdown list." 
    check = Cells(20, 3).Validation.Value 
    If check = False Then 
     Cells(20, 3).ClearContents 
     Exit Sub 
    End If 
End With