VBA错误13类型不匹配

时间:2016-06-21 12:19:16

标签: excel vba excel-vba

我正在尝试将工作表中的一行单元格添加到用户窗体中的多列列表框中。工作表中的列数也有所不同。我一直收到错误'Type mismatch'。单步执行我的代码,我发现它出现在第一个.AddItem行。我发现你不能用.AddItem添加多个项目。有没有其他方法可以做到这一点?我对vba很新。谢谢你的帮助!

Private Sub GenerateButton_Click()
  Dim i As Long, counter As Long, counter_RA As Long, x As Integer
  Dim LastColRA As Long, LastColCP As Long


  LastColRA = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
  LastColCP = Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column


  'Check to make sure that enough items were selected
  For x = 0 To ListBox2.ListCount - 1
    If ListBox2.Selected(x) Then
      counter_RA = counter_RA + 1
      With TabData.DataTable
        .AddItem Sheets(Sheet1).Range(Cells(x + 2, 1), Cells(x + 2, LastColRA)).Text
      End With
    End If
  Next x

  For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
      counter = counter + 1
      With TabData.DataTable
        .AddItem Sheets(Sheet2).Range(Cells(i + 2, 1), Cells(i + 2, LastColCP)).Text
      End With
    End If
  Next i
End Sub

1 个答案:

答案 0 :(得分:1)

你有几个问题。首先,如果您使用多个单元格区域的Text属性,它将返回Null,除非所有单元格包含相同的文本。其次,正如您所说,您无法使用AddItem一次性添加数组 - 您需要添加一个项目然后循环以填充列,记住索引是基于0的:

With TabData.DataTable
   .AddItem
   For n = 1 to LastColRA
      .List(.ListCount - 1, n - 1) = Sheet1.Cells(x + 2, n).Value
   next n
End With

这是一个可以使用超过10列的版本:

Dim i As Long, counter As Long, counter_RA As Long, x As Long
Dim LastColRA As Long, LastColCP As Long
Dim vList()


LastColRA = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
LastColCP = Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column


'Check to make sure that enough items were selected
For x = 0 To ListBox2.ListCount - 1
    If ListBox2.Selected(x) Then
        counter_RA = counter_RA + 1
        ReDim Preserve vList(1 To LastColRA, 1 To counter_RA)
        For i = 1 To LastColRA
            vList(i, counter_RA) = Sheet1.Cells(x + 2, i).Value
        Next i
    End If
Next x
For x = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(x) Then
        counter_RA = counter_RA + 1
        ReDim Preserve vList(1 To LastColRA, 1 To counter_RA)
        For i = 1 To LastColRA
            vList(i, counter_RA) = Sheet2.Cells(x + 2, i).Value
        Next i
    End If
Next x

With TabData.DataTable
    .ColumnCount = LastColRA
    .Column = vList
End With