在VB应用程序中调用Excel对象

Yuki0512 2012-04-28 11:33:56
我是从网上找到的代码,可是运行时遇到一个问题:缺少函数或变量!
希望各位高手帮忙看看,如何修改,感觉就差一点就成了,我是菜鸟,帮帮我吧!
Private Sub Command1_Click()
Dim Irow, Icol As Integer
Dim Irowcount, Icolcount As Integer
Dim Fieldlen() '存字段长度值
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

With Data1.Recordset.MoveLast

If .RecordCount < 1 Then
MsgBox ("Error 没有记录!")
Exit Sub
End If

Irowcount = .RecordCount '记录总数
Icolcount = .Fields.Count '字段总数

ReDim Fieldlen(Icolcount)
Fieldlen(Icolcount).MoveFirst

For Irow = 1 To Irowcount + 1
For Icol = 1 To Icolcount
Select Case Irow
Case 1 '在Excel中的第一行加标题
xlSheet.Cells(Irow, Icol).Value = .Fields(Icol - 1).Name
Case 2 '将数组FIELDLEN()存为第一条记录的字段长

If IsNull(.Fields(Icol - 1)) = True Then
Fieldlen(Icol) = LenB(.Fields(Icol - 1).Name)
'如果字段值为NULL,则将数组Filelen(Icol)的值设为标题名的宽度
Else
Fieldlen(Icol) = LenB(.Fields(Icol - 1))
End If

xlSheet.Columns(Icol).ColumnWidth = Fieldlen(Icol)
'Excel列宽等于字段长
xlSheet.Cells(Irow, Icol).Value = .Fields(Icol - 1)
'向Excel的CellS中写入字段值
Case Else
Fieldlen1 = LenB(.Fields(Icol - 1))

If Fieldlen(Icol) < Fieldlen1 Then
xlSheet.Columns(Icol).ColumnWidth = Fieldlen1
'表格列宽等于较长字段长
Fieldlen(Icol) = Fieldlen1
'数组Fieldlen(Icol)中存放最大字段长度值
Else
xlSheet.Columns(Icol).ColumnWidth = Fieldlen(Icol)
End If

xlSheet.Cells(Irow, Icol).Value = .Fields(Icol - 1)
End Select
Next
If Irow <> 1 Then
If Not .EOF Then .MoveNext
End If
Next
With xlSheet
.Range(.Cells(1, 1), .Cells(1, Icol - 1)).Font.Name = "黑体"
'设标题为黑体字
.Range(.Cells(1, 1), .Cells(1, Icol - 1)).Font.Bold = True
'标题字体加粗
.Range(.Cells(1, 1), .Cells(Irow, Icol - 1)).Borders.LineStyle = xlContinuous
'设表格边框样式
End With
xlApp.Visible = True '显示表格
xlBook.Save "保存 "
Set xlApp = Nothing '交还控制给Excel
End With
End Sub

...全文
92 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Yuki0512 2012-04-29
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
http://download.csdn.net/detail/veron_04/2341786
[/Quote]
我想要将access数据库与excel相连,就是打开excel里面显示的是access表中的数据。有没有这个代码?谢谢!

1,216

社区成员

发帖
与我相关
我的任务
社区描述
VB 数据库(包含打印,安装,报表)
社区管理员
  • 数据库(包含打印,安装,报表)社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧