2015-05-29 144 views
2

我想編寫一個宏,它將從下拉列表中選擇一個特定值(在我的情況下,存儲在單元格A1中)(在我的情況下,在單元格D6中)。以編程方式從Excel下拉菜單中選擇

這是我到目前爲止有:

sr_par2 = Array ("TEXT", 'TEXT2", "TEXT3") 

sr = Range("A1").Value 

(...) 

Dim i As Integer 
i = 0 
Range("D6").Select 

Do While (sr <> ActiveCell.FormulaR1C1) 
    Range("D6").Select 
    ActiveCell.FormulaR1C1 = sr_par2(i) 
    i = i + 1 
Loop 
+0

我不知道如果我理解你的問題。什麼是'sr'? 'sr <> ActiveCell.FormulaR1C1'? –

+0

sr是Cell1中需要複製的值。 – Michal

+0

和sr <> ActiveCell.FormulaR1C1在我看來應該檢查活動單元格中的值(在這種情況下是「D6」)是否現在在列表 – Michal

回答

2

這是你想什麼呢?我已經評論了該代碼,以便您不會理解它。不過,如果你不那麼簡單地問:)

Sub Sample() 
    Dim ws As Worksheet 
    Dim rngIn As Range, rngOut As Range 
    Dim MyAr 
    Dim sFormula As String 
    Dim i As Long 

    '~~> Replace this with the relevant worksheet 
    Set ws = ThisWorkbook.Sheets("Sheet1") 

    With ws 
     '~~> Set your input and output range here 
     Set rngIn = .Range("A1") 
     Set rngOut = .Range("D6") 

     '~~> Get the validation list if there is one 
     On Error Resume Next 
     sFormula = rngOut.Validation.Formula1 
     On Error GoTo 0 

     If sFormula = "" Then 
      '~~> If no validation list then directly populate the value 
      rngOut.Value = rngIn.Value 
     Else 
      'validation list TEXT1,TEXT2,TEXT3 
      MyAr = Split(sFormula, ",") 

      '~~> Loop through the list and compare 
      For i = LBound(MyAr) To UBound(MyAr) 
       If UCase(Trim(rngIn.Value)) = UCase(Trim(MyAr(i))) Then 
        rngOut.Value = MyAr(i) 
        Exit For 
       End If 
      Next i 

      '~~> Check if the cell is still blank. If it is then it means that 
      '~~> Cell A1 has a value which is not part of the list 
      If Len(Trim(rngOut.Value)) = 0 Then 
       MsgBox "The value in " & rngOut.Address & _ 
       " cannot be set as the value you are copying is not part of the list" 
      End If 
     End If 
    End With 
End Sub 
+0

看起來像我在找什麼:)但我會在一小時內回答以確保;) – Michal

0

如果我理解正確的話,這應該做你想做的:

sr_par2 = Array("TEXT", "TEXT2", "TEXT3") 

sr = Range("A1").Value 

Dim i As Integer 
i = 0 

On Error GoTo Handler 
Do While (sr <> sr_par2(i)) 
    i = i + 1 
Loop 
Range("D6").FormulaR1C1 = sr_par2(i) 

Exit Sub 
Handler: 
MsgBox "Value not in the list", vbCritical + vbOKOnly, "Value not found"