Data Excel loses and wrong formats when data is copied from ADODB recordset

61 Views Asked by At

After using ADODB recordset to paste data in Excel, some columns have lost data and some have the wrong format as below.

enter image description here

                If SheetExists(conn, sheetName) Then
                    ' Create a recordset for the sheet
                    Set rs = CreateObject("ADODB.Recordset")
                    rs.Open "SELECT * FROM [" & sheetName & "]", conn, 3, 1
                    
                    ' Copy data from the recordset to the new workbook
                    Dim destWs As Worksheet
                    Set destWs = destWb.Sheets.Add
                    'sheetname
                    leng = Len(sheetName) - 1
                    destWs.Name = Left(sheetName, leng)
                    'Copy header
                    For i = 1 To rs.Fields.Count
                        destWs.Cells(1, i).Value = rs.Fields(i - 1).Name
                    Next i
                    'copy Data
                    If Not rs.EOF Then
                    destWs.Cells(2, 1).CopyFromRecordset rs
                    End If
                    ' Close the recordset
                    rs.Close
                End If

I want the output to have the same format and correct data.

0

There are 0 best solutions below