错误381从工作表中填充列表框

时间:2018-10-14 15:41:18

标签: excel vba

我一直都出现错误381。什么地方出错了?如果我仅使用1列,则可以使用,如果我添加2nd或更多,则它将停止使用。

我尝试填充用“ if语句”编译的行。

每次在第二列工作都会停止。

UserForm +一些数据: https://drive.google.com/open?id=1hfCAu2m7C4kISSPJSvyjWc-TvxBr-fOO

第二版代码:

  Sub PopulateList2()
   Dim rngName As Range
   Dim ws As Worksheet
   Dim i As Integer
   Dim LastRow As Long

   Set ws = E1G


  With ListBoxAbg
  .Clear
  .ColumnCount = 2

  LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row

For i = 1 To LastRow
  If ws.Cells(i, 6).Value < Now() _
And ws.Cells(i, 6).Value <> vbNullString Then
      .AddItem
      .List(i - 1, 0) = ws.Cells(i, 1).Value
      .List(i - 1, 1) = ws.Cells(i, 3).Value

 End If
Next i
End With
End Sub

....

 Sub PopulateList2()
  Dim rngName As Range
  Dim ws As Worksheet
  Dim i As Integer
  Dim LastRow As Long

  Set ws = E1G



AbgeListField.Clear
AbgeListField.ColumnCount = 7

LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row

For i = 1 To LastRow
If ws.Cells(i, 6).Value < Now() _
And ws.Cells(i, 6).Value <> vbNullString Then
   AbgeListField.AddItem ws.Cells(i, 1).Value
   AbgeListField.List(i - 1, 1) = ws.Cells(i, 2).Value
   AbgeListField.List(i - 1, 2) = ws.Cells(i, 3).Value
   AbgeListField.List(i - 1, 3) = ws.Cells(i, 4).Value
   AbgeListField.List(i - 1, 4) = ws.Cells(i, 5).Value
   AbgeListField.List(i - 1, 5) = ws.Cells(i, 6).Value
   AbgeListField.List(i - 1, 6) = ws.Cells(i, 7).Value
  End If
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

我在那篇文章中找到了答案: https://social.msdn.microsoft.com/Forums/office/en-US/f5619db9-be72-41e3-a353-54ebb021f936/runtime-error-381-could-not-set-the-list-property-invalid-property-array-index?forum=exceldev

我添加了新的dim nxtItme As Long。它现在可以完美运行:

Sub PopulateList2()
 Dim rngName As Range
 Dim ws As Worksheet
 Dim i As Integer
 Dim LastRow As Long
 Dim nxtItem As Long

 Set ws = E1G
 nxtItem = 0

 With ListBoxAbg
  .Clear
  .ColumnCount = 6

  LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row

For i = 1 To LastRow
  If ws.Cells(i, 6).Value < Now() _
  And ws.Cells(i, 6).Value <> vbNullString Then

.AddItem
.List(nxtItem, 0) = ws.Cells(i, 1).Value
.List(nxtItem, 1) = ws.Cells(i, 3).Value
.List(nxtItem, 2) = ws.Cells(i, 4).Value
.List(nxtItem, 3) = ws.Cells(i, 5).Value
.List(nxtItem, 4) = ws.Cells(i, 6).Value
nxtItem = nxtItem + 1

  End If
 Next i
End With

End Sub