请教大神VB 6 DataGrid1数据导出EXCEL问题

kp333163 2020-11-13 04:16:56
用统计按钮查询出来的数据然后点导出提示424 要求对象
这个代码是从论坛里找到的。请问下这个是哪里问题,我是VB小白
Private Sub Command2_Click()
Dim i, r, c As Integer
Dim newxls As New Excel.Application '声明application 对象
Dim newbook As New Excel.Workbook
Dim newsheet As New Excel.Worksheet

Set newbook = newxls.Workbooks.Add '创建工作薄
Set newsheet = newbook.Worksheets(1) '创建工作表
With CommonDialog1
.CancelError = False '在对话框中,按cancel键不出现错误
.Flags = cdlOFNHideReadOnly & cdlOFNOverwritePrompt
.Filter = "Excel Files (*.xls)|*.xls" '对话框底部“保存文件类型“下拉匡显示的内容"
.FilterIndex = 1 '选择"保存类型"的第一个值为默认值,即"Excel Files (*.xls)|*.xls"
.ShowSave

'设置Excel内容的格式,现在暂时不用
'With newsheet
' .Cells.Font.Name = "System"
' .Cells.Font.Size = 12
' .Name = "数据列表"
'
' Range(Cells(1, 1), Cells(1, DataGrid1.Columns.Count)).Select
' Selection.HorizontalAlignment = xlCenter
' Selection.VerticalAlignment = xlCenter
' Selection.Merge '合并居中
' .Cells(1, 1) = "导出excel文件"
'End With

If rs.RecordCount > 0 Then
For i = 0 To DataGrid1.Columns.Count - 1 '循环添加表头
newsheet.Cells(2, i + 1) = DataGrid1.Columns(i).Caption
Next
rs.MoveFirst
Do Until rs.EOF
r = rs.AbsolutePosition '读取recordset对象当前记录的序号位置
For c = 0 To DataGrid1.Columns.Count - 1
DataGrid1.Col = c '读取地c列数据
newsheet.Cells(r + 2, c + 1) = DataGrid1.Columns(c)
Next
rs.MoveNext
Loop
End If

newsheet.SaveAs FileName:=CommonDialog1.FileName
newbook.Close
newxls.Quit
Set newbook = Nothing
Set newsheet = Nothing
Set newxls = Nothing
Set conn = Nothing
Set rs = Nothing

End With
MsgBox "数据导出成功", vbMsgBoxRight, "提示"
End Sub
...全文
104 点赞 收藏 回复
写回复
回复
切换为时间正序
请发表友善的回复…
发表回复
相关推荐
发帖
控件
创建于2007-09-28

1428

社区成员

VB 控件
申请成为版主
帖子事件
创建了帖子
2020-11-13 04:16
社区公告
暂无公告