From Recordset to Excel - Heeyoung-Ahn/Excel_VBA GitHub Wiki

์ปฌ๋Ÿผ์ด๋ฆ„ ๋ฐ˜ํ™˜

For i = 0 To rs.Fields.Count - 1
    Cells(1, 1).Offset(0, i).Value = rs.Fields(i).Name
Next i

๋ ˆ์ฝ”๋“œ ๋ฐ˜ํ™˜

  • ๋ฐฉ๋ฒ•1) Range.CopyFromRecordset Method ์‚ฌ์šฉ
    Cells(2, 1).CopyFromRecordset rs
  • ๋ฐฉ๋ฒ•2) RecordSet.GetRows Method ์‚ฌ์šฉ
    Cells(2, 1).Resize(rs.RecordCount, rs.Fields.Count) = Application.WorksheetFunction.Transpose(rs.GetRows)
    • GetRows: ๋ ˆ์ฝ”๋“œ ์ง‘ํ•ฉ ๊ฐœ์ฒด์˜ ์—ฌ๋Ÿฌ ๋ ˆ์ฝ”๋“œ๋ฅผ 2์ฐจ์› ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜(Variant)
    • ์ด๋•Œ, GetRows ๋ฐฐ์—ด์€ ์—ด X ํ–‰์œผ๋กœ ๋˜์–ด ์žˆ์–ด์„œ ์—‘์…€์—์„œ ๋ฐ›์„ ๋•Œ Tranposeํ•ด์„œ ๋ฐ›์•„์•ผ ํ•จ

UserForm์˜ ListBox์— ๋ฐ˜ํ™˜1

DB โ†’ RecordSet โ†’ UserForm ListBox

With Me.lst1
    .ColumnCount = rs.Fields.Count
    .ColumnHeads = False
    .ColumnWidths = "0,100,50,100,50,70,100,0,50"
    .Width = 530
    .TextAlign = fmTextAlignLeft
    .Font = "๋ง‘์€ ๊ณ ๋”•"
    .Column = rs.GetRows
End With

UserForm์˜ ListBox์— ๋ฐ˜ํ™˜2

DB์˜ Null๊ฐ’ ์ œ์–ด ํ•„์š”์‹œ ์‚ฌ์šฉ
DB โ†’ RecordSet โ†’ Array โ†’ UserForm ListBox

With Me.lst1
    .ColumnCount = rs.Fields.Count
    .ColumnHeads = False
    .ColumnWidths = "0,100,50,100,50,70,100,0,50"
    .Width = 530
    .TextAlign = fmTextAlignLeft
    .Font = "๋ง‘์€ ๊ณ ๋”•"
End With

If Not rs.EOF Then
    ReDim listData(0 To rs.RecordCount - 1, 0 To rs.Fields.Count - 1)
    rs.MoveFirst
    For i = 0 To rs.RecordCount - 1
        For j = 0 To rs.Fields.Count - 1
            If IsNull(rs.Fields(j).Value) = True Then
                listData(i, j) = ""
            Else
                listData(i, j) = rs.Fields(j).Value
            End If
        Next j
        rs.MoveNext
    Next i
End If

On Error Resume Next
    cntRecord = UBound(listData) - LBound(listData) + 1
On Error GoTo 0
If cntRecord = 0 Then
    MsgBox "๋ฆฌ์ŠคํŠธ์— ๋ฐ˜ํ™˜ํ•  DB ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", vbInformation, Banner
    argListBox.Clear
    Me.txt_count.Value = argListBox.ListCount
    Exit Sub
End If

argListBox.List = listData
Me.txt_count.Value = argListBox.ListCount