2016-11-10 32 views
0

當用戶可以單擊該按鈕時,我有兩個帶有一個按鈕的列表框,將所有列表項從列表框1移動到列表框2。當爲ListBox是變空的應用是越來越重新啓動,EXCEL 2016列表框項目清除功能在VBA Excel中不起作用

我的代碼是

For i = 1 To ThisWorkbook.Sheets("MultiSheet").ListBoxes(strFromlb).listCount 
    ThisWorkbook.Sheets("MultiSheet").ListBoxes(strTolb).AddItem ThisWorkbook.Sheets("MultiSheet").ListBoxes(strFromlb).List(1) 
    ThisWorkbook.Sheets("MultiSheet").ListBoxes(strFromlb).RemoveItem (1) 
Next i 

這裏strFromLb被清除值,但是當它清除最後一個值我的VBA程序是Excel中已重新啓動。

然後我試圖代碼以清除列表框

ThisWorkbook.Sheets("MultiSheet").ListBoxes(strFromlb).ControlFormat.RemoveAllItems 
ThisWorkbook.Sheets("MultiSheet").ListBoxes(strFromlb).Items.Clear 

該錯誤是

「對象犯規支撐到屬性或方法」

然後

ThisWorkbook.Sheets("MultiSheet").ListBoxes(strFromlb).Clear 

這段代碼我得到了400錯誤。好心幫助我。

回答

0
Worksheets("MultiSheet").ListBoxes(strFromlb).ControlFormat.‌​RemoveAllItems 
+0

清除功能,是不是一個屬性或方法 –

+0

這些錯誤我得到 –

+0

試圖通過他們的名字(即訪問列表框。 strFromlb.Clear),而不是功能Listboxes(「...」) – cullan

0

參考:The Complete Guide to Excel VBA Form Control ListBoxes

存在用於工作表形式的控制和MsForms ActiveX控件兩個式列表框控件。 getListBox將返回得到任一。

你的代碼中有幾個語法錯誤的

  • Listbox.List返回一個0基於陣列
  • 使用RemoveItem的時候,因爲它是不是一個函數
你不使用括號
Dim lBoxFrom As Object, lBoxTo As Object 

Set lBoxFrom = getListBox("MultiSheet", strFromlb) 
Set lBoxTo = getListBox("MultiSheet", strTolb) 

For i = 0 To lBoxFrom.ListCount - 1 
    lBoxTo.AddItem lBoxFrom.List(1) 
    lBoxFrom.RemoveItem 1 
Next 

lBoxTo.List = lBoxFrom.List 
lBoxFrom.Clear 

Sub Test() 
    Const WORKSHEET_NAME = "Sheet1" 
    Const strFromlb = "BoxFrom" 
    Const strTolb = "BoxTo" 

    Dim lBoxFrom As Object, lBoxTo As Object 
    Dim i As Integer 
    Set lBoxFrom = getListBox(WORKSHEET_NAME, strFromlb) 
    Set lBoxTo = getListBox(WORKSHEET_NAME, strTolb) 
    lBoxFrom.AddItem "A" 
    lBoxFrom.AddItem "B" 
    lBoxFrom.AddItem "C" 

    For i = 0 To lBoxFrom.ListCount - 1 
     lBoxTo.AddItem lBoxFrom.List(0) 
     lBoxFrom.RemoveItem 0 
    Next 

End Sub 

Function getListBox(WorkSheetName As String, ListBoxName As String) As Object 
    Dim lBox As Object 
    On Error Resume Next 
    Set lBox = Worksheets(WorkSheetName).ListBoxes(ListBoxName) 
    On Error GoTo 0 

    If lBox Is Nothing Then 
     On Error Resume Next 
     Set lBox = Worksheets(WorkSheetName).Shapes(ListBoxName).OLEFormat.Object.Object 
     On Error GoTo 0 
    End If 
    Set getListBox = lBox 
End Function 
+0

你在函數結尾缺少一個'Set getListBox = lBox'。更重要的是,我將它縮短到'Function GetListBox(WorkSheetName As String,ListBoxName As String)As Object/Dim lBox As Object/On Error Resume Next/Set lBox = Worksheets(WorkSheetName)。ListBoxes(ListBoxName)/ If lBox Is Nothing Then Set lBox = Worksheets(WorkSheetName).Shapes(ListBoxName).OLEFormat.Object/On Error GoTo 0/Set GetListBox = lBox/End Function' – user3598756

+0

再次感謝@ user3598756。最近我一直匆匆忙忙。 – 2016-11-10 07:15:18

+0

雅,但仍然是工作表重新啓動時列表框爲空 –