Home » excel » excel – Run-Time error 13 Type Mismatch in workbook.worksheets

excel – Run-Time error 13 Type Mismatch in workbook.worksheets

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am getting

Run-time error 13: Type mismatch

on my code below:

Dim C As Integer, CoSheet As Worksheet

For Each CoSheet In Workbooks(ListBoxWbk.Value).Worksheets
    For C = 1 To 10
        'Error on code below
        Sheet2.Range("A1048573").End(xlUp).Offset(1, 0).Value = Workbooks(ListBoxWbk.Value).Sheets(CoSheet).Cells(1, 15) & "-1"
        Sheet2.Range("B1048573").End(xlUp).Offset(1, 0).Value = Workbooks(ListBoxWbk.Value).Sheets(CoSheet).Cells(C, 2)
        Sheet2.Range("C1048573").End(xlUp).Offset(1, 0).Value = Workbooks(ListBoxWbk.Value).Sheets(CoSheet).Cells(C, 4)
        Sheet2.Range("D1048573").End(xlUp).Offset(1, 0).Value = Workbooks(ListBoxWbk.Value).Sheets(CoSheet).Cells(C, 5)
        Sheet2.Range("E1048573").End(xlUp).Offset(1, 0).Value = Workbooks(ListBoxWbk.Value).Sheets(CoSheet).Cells(C, 6)
        Sheet2.Range("F1048573").End(xlUp).Offset(1, 0).Value = Workbooks(ListBoxWbk.Value).Sheets(CoSheet).Cells(C, 7)
    Next C
Next CoSheet
How to&Answers:

All your lines with:

Workbooks(ListBoxWbk.Value).Sheets(CoSheet)...

Should be replaced with:

CoSheet... 

Modified Code

For Each CoSheet In Workbooks(ListBoxWbk.Value).Worksheets
    For C = 1 To 10
        Sheet2.Range("A1048573").End(xlUp).Offset(1, 0).Value = CoSheet.Cells(1, 15) & "-1"
        Sheet2.Range("B1048573").End(xlUp).Offset(1, 0).Value = CoSheet.Cells(C, 2)
        Sheet2.Range("C1048573").End(xlUp).Offset(1, 0).Value = CoSheet.Cells(C, 4)
        Sheet2.Range("D1048573").End(xlUp).Offset(1, 0).Value = CoSheet.Cells(C, 5)
        Sheet2.Range("E1048573").End(xlUp).Offset(1, 0).Value = CoSheet.Cells(C, 6)
        Sheet2.Range("F1048573").End(xlUp).Offset(1, 0).Value = CoSheet.Cells(C, 7)
    Next C
Next CoSheet

Note: if you are trying to paste at the first empty row, you could use something like the code below:

Dim C As Integer, CoSheet As Worksheet
Dim LastRow As Long

For Each CoSheet In Workbooks(ListBoxWbk.Value).Worksheets
    For C = 1 To 10
        LastRow = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row ' <-- getting last row in column "A"

        Sheet2.Range("A" & LastRow + 1).Value = CoSheet.Cells(1, 15) & "-1"
        Sheet2.Range("B" & LastRow + 1).Value = CoSheet.Cells(C, 2)
        Sheet2.Range("C" & LastRow + 1).Value = CoSheet.Cells(C, 4)
        Sheet2.Range("D" & LastRow + 1).Value = CoSheet.Cells(C, 5)
        Sheet2.Range("E" & LastRow + 1).Value = CoSheet.Cells(C, 6)
        Sheet2.Range("F" & LastRow + 1).Value = CoSheet.Cells(C, 7)
    Next C
Next CoSheet