2013-07-16 19 views
2

有沒有辦法在提示本身產生具有多個選項的輸入提示。用戶可以選擇任何一個提供的選項。截至目前,我正在使用「輸入字符串」,然後設置變量的值。例如: 要選擇哪張表? Sheet1? Sheet2? Sheet3?帶選項的輸入提示

+1

什麼'輸入提示'和'輸入字符串'?您使用的是什麼功能:數據驗證或某種形式的組合框?你需要澄清你的問題。 –

回答

1

如果你的意思是使用的InputBox()函數:

答:不,你不能。 InputBox內置於VBA中,無法修改。

但是你可以編寫你自己的InputBox。做這個:

  1. 您必須創建一個名爲formComboInput與組合框,標籤和按鈕等

  2. 用戶窗體創建一個名爲ReturnVal在窗體的代碼公用整型變量。

  3. 將-1的值賦值給FormComboInput.InialiseForm子類中的ReturnVal,並在該子元素中填充組合框。

  4. 在用戶窗體按鈕中單擊代碼,將formComboInput.comboInput.ListIndex的值賦給ReturnVal,並隱藏窗體。

當窗體加載時,使用子例程(如InitialiseForm())填充組合框。您可以將組合框範圍存儲在單獨的工作表或靜態數組中。

然後插入類似如下(未經測試對不起)代碼:

' User form code: 
Option Explicit 

public ReturnVal as integer 

sub InitialiseForm()   
    dim i as integer 

    ReturnVal = -1 

    comboInput.Clear 

    for i = 1 to ThisWorkbook.Worksheets.Count ' Populates combobox 
     comboInput.AddItem ThisWorkbook.Worksheets(i).Name 
    next 

end sub 

btnOK_Click() 
    ReturnVal = comboInput.ListIndex ' Change ReturnVal from -1 to the listbox index 
    Me.Hide 
End Sub 

' Module/sheet code: 
Option Explicit 

function ShowComboInput(InputBoxCaption as String, DefaultResult as String) as String 

    with formComboInput 
     .InitialiseForm() ' Make the combo box populate etc 
     .labelCaption = InputBoxCaption 
     .Show vbModal ' CODE EXECUTION PAUSES HERE UNTIL FORM IS CLOSED 

     if .ReturnVal > -1 then 
      ShowComboInput = .comboInput.Value ' Returned if user clicks OK button 
     else 
      ShowComboInput = DefaultResult ' Returned if user closes form 
     end if 

    end with 

end function 


sub InputBoxExample() ' Call this sub to test the above code 

    MsgBox ShowComboInput("Testing", "User didn't click OK button!") 

end sub 

此代碼是未經測試,可能需要一些調整,但總的來說,這是我將如何實現自定義的輸入框。

相關問題