Run time error 381 vba excel

I am using the following code to pull data from a worksheet and drop it into a listbox on a form. The code works fine if the If statement is not there, or if I remove the condition and change it to true, but with the code as written, I get the error indicated in the subject line. Any suggestions for how to fix this?
  • Remove From My Forums
  • Question

  • I am using the following code to pull data from a worksheet and drop it into a listbox on a form. The code works fine if the If statement is not there, or if I remove the condition and change it to true, but with the code as written, I get the error indicated
    in the subject line. Any suggestions for how to fix this?

    Private Sub UserForm_Activate()
        Dim woFields(7) As String
        Dim wos() As Variant
        Dim ws As Worksheet
        Dim woRng As Range
        Dim r As Range
        Dim strTest As String
        Dim i As Integer
        Dim numRows As Integer
        Dim workRow As Integer
        Dim varTest As Variant
        
        
        Set ws = Worksheets("MaximoImport")
        Set woRng = ws.UsedRange
        numRows = ws.UsedRange.Rows.Count
        ReDim wos(numRows)
        For workRow = 2 To numRows
        
        
        If (woRng.Cells(workRow, 24) <> "X") Then
          With Me.lstBoxWos
                .AddItem
                .List(workRow - 2, 0) = woRng.Cells(workRow, 21)
                .List(workRow - 2, 1) = woRng.Cells(workRow, 4)
                .List(workRow - 2, 2) = woRng.Cells(workRow, 9)
                .List(workRow - 2, 3) = woRng.Cells(workRow, 22)
                .List(workRow - 2, 4) = woRng.Cells(workRow, 23)
                .List(workRow - 2, 5) = woRng.Cells(workRow, 5)
                .List(workRow - 2, 6) = woRng.Cells(workRow, 7)
          End With
        End If
        
        
        Next workRow
        
    End Sub
    

    Thanks,

    Ray

Answers

  • This happens because when you are skipping a cell that has X your workRow variable increments as well. 

    So if you add row 2 and 3 and skip 4 and try to add 5 then you have got index 4 empty. 

    You could modify the for loop a bit adding an extra variable nxtItem to keep track of the index to add to

    For workRow = 2 To numRows
        
        Dim nxtItem As Long
        nxtItem = 0
        
        If (UCase(woRng.Cells(workRow, 24)) <> "X") Then
          With Me.lstBoxWos
                .AddItem
                .List(nxtItem, 0) = woRng.Cells(workRow, 21)
                .List(nxtItem, 1) = woRng.Cells(workRow, 4)
                .List(nxtItem, 2) = woRng.Cells(workRow, 9)
                .List(nxtItem, 3) = woRng.Cells(workRow, 22)
                .List(nxtItem, 4) = woRng.Cells(workRow, 23)
                .List(nxtItem, 5) = woRng.Cells(workRow, 5)
                .List(nxtItem, 6) = woRng.Cells(workRow, 7)
                nxtItem = nxtItem + 1
          End With
        End If
    Next workRow
    

    and increment that variable every time a new item has been added to the list.

    Also, make sure your ListBox.Column property is set to 7.

    • Proposed as answer by

      Thursday, October 2, 2014 1:56 PM

    • Marked as answer by
      Fei XueMicrosoft employee
      Wednesday, October 8, 2014 10:00 AM

  1. 12-14-2012, 10:08 AM


    #1

    eemiller1997 is offline


    Forum Contributor


    Excel run-time error ‘381’: Could not set the List property. Invalid property array index

    I have a Multi-Page Userform and I’ve been able to test the userform many times, then suddently yesterday I get this «run-time error ‘381’: Could not set the List property. Invalid property array index.»

    I’m not sure why I am now getting this. I made changes to the form yesterday, but not changes to anything to warrent this problem. Now I can’t even test this form, let alone use it.

    Please help.

    Here is the code that the debug takes me to.


  2. 12-14-2012, 10:09 AM


    #2

    Are there any candidates listed on CandidateData?

    If there are how many?

    If posting code please use code tags, see here.


  3. 12-14-2012, 10:13 AM


    #3

    eemiller1997 is offline


    Forum Contributor


    Re: Excel run-time error ‘381’: Could not set the List property. Invalid property array in

    one. I had tried to enter three, but I had done it wrong. I had entered a candidate’s data and didn’t press add/update because I wanted to see if it would work to enter a second and third and then finally press add/update. But that didn’t work. It only added the one. I was just playing around to see how the form is working. So, just one candidate.


  4. 12-14-2012, 10:16 AM


    #4

    Only one candidate is the problem, not the code.

    You need to adjust the code to check for the no of candidates.

    If there is only one candidate use AddItem, if there’s more than one use List.


  5. 12-14-2012, 10:19 AM


    #5

    eemiller1997 is offline


    Forum Contributor


    Re: Excel run-time error ‘381’: Could not set the List property. Invalid property array in

    How do I adjust the code to accomodate that? What do you mean by using List if there is more than one?


  6. 12-14-2012, 10:33 AM


    #6

    The code already uses List t populate the combobox.

    List won’t work if there’s only one candidate.

    Try this, but be warned this is roughly written code and is probably prone to errors — don’t have IntelliSense on my phone.


  7. 12-14-2012, 12:09 PM


    #7

    eemiller1997 is offline


    Forum Contributor


    Re: Excel run-time error ‘381’: Could not set the List property. Invalid property array in

    That seems to have worked. I tested it by entering one candidate name and information and clicking add/update. Then, I closed the box and reopened it using my macro box on the form to re-open the userform and it opened just fine. Thank you


  8. 12-20-2012, 11:44 AM


    #8

    eemiller1997 is offline


    Forum Contributor


    Re: Excel run-time error ‘381’: Could not set the List property. Invalid property array in

    So, this error was showing elswhere, but now it’s showing under the frmPrintCand…. what could be the problem.

    Changing Attachment, please use this one.

    ComboBoxPrintBox_TroublesV10.xlsm

    Last edited by eemiller1997; 12-20-2012 at 11:46 AM.


  9. 12-20-2012, 12:48 PM


    #9

    eemiller1997 is offline


    Forum Contributor


    Re: Excel run-time error ‘381’: Could not set the List property. Invalid property array in

    It’s been figured out. Yay!

    The changes in red were necessary:


 

kacagevici

Пользователь

Сообщений: 70
Регистрация: 01.01.1970

Уважаемые гуру при нажатии клавиш del,backspace,escape(чтобы очистить форму) combo box активен выдает ошибку следующего типа:  
run-time error ‘381’: Could not get the List property.Invalid property array index.  

  Вот код из user form:  

  Option Explicit  
Private Sub Combobox1_Change()  
Dim iSotrud As String  
   iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex)  
    If ActiveSheet.AutoFilterMode Then  
   Range(«b1»).AutoFilter Field:=2, Criteria1:=iSotrud  
   End If  
   UserForm2.StartUpPosition = 2  
End Sub  
Private Sub CommandButton1_Click()  
Selection.AutoFilter Field:=2  
End Sub  
Private Sub UserForm_Initialize()  
   Dim AllCells As Range, Cell As Range  
   Dim NoDupes As New Collection  
   Dim i As Integer, j As Integer  
   Dim Swap1, Swap2, Item  
   Set AllCells = Range(«b2:b» & Cells(Rows.Count, 2).End(xlUp).Row)  
   On Error Resume Next  
   For Each Cell In AllCells  
       NoDupes.Add Cell.Value, CStr(Cell.Value)  
   Next Cell  
   On Error GoTo 0  
   For i = 1 To NoDupes.Count — 1  
       For j = i + 1 To NoDupes.Count  
           If NoDupes(i) > NoDupes(j) Then  
               Swap1 = NoDupes(i)  
               Swap2 = NoDupes(j)  
               NoDupes.Add Swap1, before:=j  
               NoDupes.Add Swap2, before:=i  
               NoDupes.Remove i + 1  
               NoDupes.Remove j + 1  
           End If  
       Next j  
   Next i  
   For Each Item In NoDupes  
       UserForm2.ComboBox1.AddItem Item  
   Next Item  
End Sub  

  почему не получается очистить форму ?  
где ошибка?

 

The_Prist

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

На этой строке?  
iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex)  

  Может потому, что при пустом значении ListIndex = -1 и это стоит отслеживать?  
If Me.ComboBox1 = «» then exit sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

kacagevici

Пользователь

Сообщений: 70
Регистрация: 01.01.1970

да на строке  
iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex)

 

The_Prist

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=kacagevici}{date=07.10.2010 03:27}{thema=}{post}да на строке  
iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex){/post}{/quote}И? Я ж написал, что сделать.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

kacagevici

Пользователь

Сообщений: 70
Регистрация: 01.01.1970

{quote}{login=The_Prist}{date=07.10.2010 03:29}{thema=Re: }{post}{quote}{login=kacagevici}{date=07.10.2010 03:27}{thema=}{post}да на строке  
iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex){/post}{/quote}И? Я ж написал, что сделать.{/post}{/quote}  

  Option Explicit  
Private Sub Combobox1_Change()  
Dim iSotrud As String  
   iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex = -1)  
    If ActiveSheet.AutoFilterMode Then  
   Range(«b1»).AutoFilter Field:=2, Criteria1:=iSotrud  
   End If  
   UserForm2.StartUpPosition = 2  
End Sub  
Private Sub CommandButton1_Click()  
Selection.AutoFilter Field:=2  
End Sub  
Private Sub UserForm_Initialize()  
   Dim AllCells As Range, Cell As Range  
   Dim NoDupes As New Collection  
   Dim i As Integer, j As Integer  
   Dim Swap1, Swap2, Item  
   Set AllCells = Range(«b2:b» & Cells(Rows.Count, 2).End(xlUp).Row)  
   On Error Resume Next  
   For Each Cell In AllCells  
       NoDupes.Add Cell.Value, CStr(Cell.Value)  
   Next Cell  
   On Error GoTo 0  
   For i = 1 To NoDupes.Count — 1  
       For j = i + 1 To NoDupes.Count  
           If NoDupes(i) > NoDupes(j) Then  
               Swap1 = NoDupes(i)  
               Swap2 = NoDupes(j)  
               NoDupes.Add Swap1, before:=j  
               NoDupes.Add Swap2, before:=i  
               NoDupes.Remove i + 1  
               NoDupes.Remove j + 1  
           End If  
       Next j  
   Next i  
   For Each Item In NoDupes  
       UserForm2.ComboBox1.AddItem Item  
   Next Item  
End Sub  

    -1 я поставил а остальное подскажи пожалуйста в какую строку ).

 

The_Prist

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Вот же блин…не так Вы все поняли. На фиг не надо -1.  

  Private Sub Combobox1_Change()  
If Me.ComboBox1 = «» then exit sub  
Dim iSotrud As String  
iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

kacagevici

Пользователь

Сообщений: 70
Регистрация: 01.01.1970

{quote}{login=The_Prist}{date=07.10.2010 03:42}{thema=}{post}Вот же блин…не так Вы все поняли. На фиг не надо -1.  

  Private Sub Combobox1_Change()  
If Me.ComboBox1 = «» then exit sub  
Dim iSotrud As String  
iSotrud = Me.ComboBox1.List(Me.ComboBox1.ListIndex){/post}{/quote}  
думаю быстрее будет только с файлом )))  
а то выдает только ошибки.

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

Попробуйте такой вариант для ComboBox1_Change:  

  Private Sub ComboBox1_Change()  
 On Error Resume Next  
 Dim s As String  
 s = ComboBox1.Value  
 With ActiveSheet  
   If .AutoFilterMode Then  
     If Len(s) = 0 Then  
       .ShowAllData  
     Else  
       .AutoFilter.Range.AutoFilter 2, s  
     End If  
   End If  
 End With  
 ‘UserForm2.StartUpPosition = 2  
End Sub

 

kacagevici

Пользователь

Сообщений: 70
Регистрация: 01.01.1970

#9

08.10.2010 10:02:41

{quote}{login=ZVI}{date=08.10.2010 05:17}{thema=}{post}Попробуйте такой вариант для ComboBox1_Change:  

  Private Sub ComboBox1_Change()  
 On Error Resume Next  
 Dim s As String  
 s = ComboBox1.Value  
 With ActiveSheet  
   If .AutoFilterMode Then  
     If Len(s) = 0 Then  
       .ShowAllData  
     Else  
       .AutoFilter.Range.AutoFilter 2, s  
     End If  
   End If  
 End With  
 ‘UserForm2.StartUpPosition = 2  
End Sub{/post}{/quote}  

    то что надо! спасибо огромное!

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • [RESOLVED] Run-Time Error 381

  1. Aug 14th, 2006, 02:58 PM


    #1

    Joe_Thomas is offline

    Thread Starter


    New Member


    Resolved [RESOLVED] Run-Time Error 381

    Hello. I am using VBA for Excel 2003. I am trying to loop through a list of items in a listbox one by one to see if any of the entries in the listbox equal a certain value. I’ve got the loop part sorted out, and have placed each list entry into a variable to be tested one by one. Part of the code is shown below (code is shown in blue, comments in green):For lstIndex = 0 To List1.ListCount
    ‘ For lstIndex 0 to the number of entries in the listboxCheckEntry = List1.List(lstIndex)
    ‘ Move the list entry into the variable «CheckEntry» where the particular list entry is defined by lstIndex which increments of course by 1 every time the loop runsIf CheckEntry = «Hello»lstFinalWordList.AddItem CheckWord
    ‘ Output the Value of «Checkword» to another list box if the condition is metEnd IfNext lstIndex

    The problem is when the loop reaches the last entry in the listbox and tries to put it into the variable «CheckEntry», The following error occurs:

    Run-time error ‘381’:
    Could not get the List Property. Invalid property array index.

    I dont understand how the loop works for all but the last item in the listbox. It dosent matter whether or not i use the ListCount property to indicate the end of the list or if i use a standard number, the same error occurs. The Line of code the program dosent like for the last listbox entry is of course:

    CheckEntry = List1.List(lstIndex)

    I would appreciate any help offered to solve this problem. Thankyou.


  2. Aug 14th, 2006, 04:13 PM


    #2

    Re: Run-Time Error 381

    Suppose you have 3 items.

    The list starts at 0. Therefore the index of item 1 is 0. Therefore the index of item 2 is 1. The index of item 3 is 2.

    Hence you don’t want to loop to list1.listcount, because the listcount is 3, but there is no item three. The last item is number 2.

    Understand?

    zaza


  3. Aug 14th, 2006, 04:34 PM


    #3

    Joe_Thomas is offline

    Thread Starter


    New Member


    Re: Run-Time Error 381

    Yeh good call zaza, thanks a lot, i forgot about that. That explains why it didnt work even when i used a standard number instead of using the listcount property. Cheers.


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • [RESOLVED] Run-Time Error 381


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

  • #1

Hi, I am trying to work on macro for a leave application module but that error pop out. I hope you could help me. Thanks in advance. Here is my code:

Code:

Private Sub ComboBox1_Change()

Sheet3.Activate

Dim mytext As Long

mytext = Me.ComboBox1.List(Me.ComboBox1.ListIndex)
TextBox1.Text = Application.WorksheetFunction.VLookup(mytext, Range("A1:E69"), 2, 0)
TextBox2.Text = Application.WorksheetFunction.VLookup(mytext, Range("A1:E69"), 3, 0)
TextBox3.Text = Application.WorksheetFunction.VLookup(mytext, Range("A1:E69"), 4, 0)


End Sub

Private Sub cmdSave_Click()

Sheet4.Activate

If Range("A2") <> "" Then
Rows("2:2").Select
Selection.Insert Shift:=xlDown
End If

If Range("A2") = "" Then
Range("A2") = Me.ComboBox1.Value
Range("B2") = Me.TextBox1.Value
Range("C2") = CDate(Me.TextBox4)
Range("D2") = Me.TextBox2.Value
Range("E2") = Me.TextBox6.Value
Range("F2") = CDate(Me.txtStartDate)
Range("G2") = CDate(Me.txtEndDate)
Range("H2") = Me.ComboBox4.Value
Range("I2") = Me.TextBox5.Value
Range("J2") = Me.TextBox3.Value
End If

Me.ComboBox1.Value = ""
Me.TextBox1.Value = ""
Me.TextBox4.Value = ""
Me.TextBox2.Value = ""
Me.TextBox6.Value = ""
Me.txtStartDate.Value = ""
Me.ComboBox4.Value = ""
Me.TextBox5.Value = ""
Me.TextBox3.Value = ""


Range("L1").Select

End Sub

Private Sub cmdClose_Click()

Unload Me

End Sub

Private Sub cmdReset_Click()

TextBox1.Value = ""
TextBox4 = ""
TextBox2 = ""
TextBox6 = ""
ComboBox4 = ""
TextBox5 = ""
TextBox3 = ""

End Sub


Private Sub UserForm_Click()

TextBox4.Text = Format(Now(), "Short Date")

End Sub

Last edited by a moderator: Sep 23, 2018

What did Pito Salas invent?

Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.

  • #2

Hi,
welcome to forum

try changing

Code:

Dim mytext As Long


mytext = Me.ComboBox1.List(Me.ComboBox1.ListIndex)

to this

Code:

Dim mytext As Variant


mytext = Me.ComboBox1.Text

and see if solves the issue

Dave

  • #3

Thank you Dave for welcoming me in this group and thanks for the help. However, when I changed the code, this error prompt:

Run-time error ‘1004’: Unable to get the Vlookup property of the WorksheetFunction class

Fluff

Fluff

MrExcel MVP, Moderator


  • #4

In that case it probably couldn’t find the value of «mytext» in A1:A69.
What sort of values does your combo hold?

  • #5

Thank you Dave for welcoming me in this group and thanks for the help. However, when I changed the code, this error prompt:

Run-time error ‘1004’: Unable to get the Vlookup property of the WorksheetFunction class

Hi,
I have done a quick test with the updated code & works fine — so as Fluff suggests, likely that search value cannot be found.

Perhaps share with us some sample data & sure forum can resolve for you

Dave

Last edited: Sep 23, 2018

  • #6

In that case it probably couldn’t find the value of «mytext» in A1:A69.
What sort of values does your combo hold?

Hi Fluff,

It includes LookUpList as per below. I created in the name manager «mytext» which equals to LookUpList!$A$2:$E$69″.

EMPLOYEE ID NUMBER EMPLOYEE NAME TEAM Team Leader OFFICE EMAIL ADDRESS

<colgroup><col width=»77″><col width=»182″><col width=»141″><col width=»148″><col width=»157″></colgroup><tbody>

</tbody>

That code under ComboBox1 is the employee ID number and in which the 3 text boxes are dependent to ComboBox1.

  • #7

Hi,
I have done a quick test with the updated code & works fine — so as Fluff suggests, likely that search value cannot be found.

Perhaps share with us some sample data & sure forum can resolve for you

Dave

Will try to explain a bit as not sure how to attach images here. Sorry.

Fluff

Fluff

MrExcel MVP, Moderator


  • #8

If they are numbers try

Code:

Dim mytext As Long


mytext = CLng(Me.ComboBox1.Text)

  • #9

If they are numbers try

Code:

Dim mytext As Long


mytext = CLng(Me.ComboBox1.Text)

Now it says Run time error ’13’:

Type Mismatch

Fluff

Fluff

MrExcel MVP, Moderator


  • #10

Can you give some examples of the combobox values.

DanteAmor

Понравилась статья? Поделить с друзьями:
  • Run time error 380 vba excel
  • Run time error 380 invalid property value перевод
  • Run time error 380 could not set the rowsource property invalid property value
  • Run time error 372
  • Run time error 3706 не удается найти указанный поставщик вероятно он установлен неправильно