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