急急急!!怎样在excel添加一个工作表?在线等....

tsh1979 2003-12-07 02:01:17
窗体里面有两个msflexgrid,要导出到excel的两个工作表sheet1,sheet2.可excel默认的只有一个,怎么解决?代码如下:

Dim Rs_Data As New ADODB.Recordset
Dim Irowcount As Integer
Dim Icolcount As Integer

Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlBook1 As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlQuery As Excel.QueryTable

With Rs_Data
If .State = adStateOpen Then
.Close
End If
.ActiveConnection = cn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockReadOnly
.Source = strOpen
.Open
End With
With Rs_Data
If .RecordCount < 1 Then
MsgBox ("没有记录!")
Exit Sub
End If
Irowcount = .RecordCount '记录总数
Icolcount = .Fields.Count '字段总数
End With

Set xlApp = CreateObject("Excel.Application")
Set xlBook = Nothing
Set xlSheet = Nothing
Set xlBook = xlApp.Workbooks().Add
xlApp.Workbooks.Add
xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets.Add
Set xlSheet = xlBook.Worksheets("sheet2")
xlApp.Visible = True

'添加查询语句,导入EXCEL数据
Set xlQuery = xlSheet.QueryTables.Add(Rs_Data, xlSheet.Range("a1"))

With xlQuery
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
End With

xlQuery.FieldNames = True '显示字段名
xlQuery.Refresh
...全文
1673 点赞 收藏 7
写回复
7 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
programkitty 2003-12-08
同意楼主
回复
taosihai1only 2003-12-08
if xlBook.Worksheets.Count <2 Then
Set xlSheet2 = xlBook.Worksheets.Add
else
Set xlSheet2 = xlBook.Worksheets(2)
end if
另外:
其实也可以在excel设置中解决.
工具->选项->常规->新工作薄中的工作表表数 设为3
回复
simanh 2003-12-07
xlBook1.workSheets.add
回复
hhjjhjhj 2003-12-07
呵还有
已有new了(Dim xlApp As New Excel.Application)
这句就不要了(Set xlApp = CreateObject("Excel.Application"))
回复
hhjjhjhj 2003-12-07
..............
Dim xlSheet1 As Excel.Worksheet
Dim xlQuery1 As Excel.QueryTable
Dim xlSheet2 As Excel.Worksheet
Dim xlQuery2 As Excel.QueryTable
.........
........
Set xlApp = CreateObject("Excel.Application")
'Set xlBook = Nothing
'Set xlSheet = Nothing
Set xlBook = xlApp.Workbooks.Add
'xlApp.Workbooks.Add
'xlApp.Workbooks.Add
Set xlSheet1 = xlBook.Worksheets(1)
'=======
if xlBook.Worksheets.Count <2 Then
Set xlSheet2 = xlBook.Worksheets.Add
else
Set xlSheet2 = xlBook.Worksheets(2)
end if
'=======
xlApp.Visible = True
Set xlQuery1 = xlSheet1.QueryTables.Add(Rs_Data, xlSheet1.Range("a1"))
.........
........
Set xlQuery2 = xlSheet2.QueryTables.Add(Rs_Data, xlSheet2.Range("a1"))
.......
.........
回复
JoAiron 2003-12-07
在excel里录制宏就可以得到代码了
选择工具----宏-----录制新宏

录制结束后,停止录制

工具----宏-----vb编辑器

就可以看到刚才的动作所对应的代码了
回复
JoAiron 2003-12-07

Sheets.Add
Sheets("Sheet4").Select
Sheets("Sheet4").Name = "12233"
回复
相关推荐
发帖

1187

社区成员

VB 数据库(包含打印,安装,报表)
申请成为版主
帖子事件
创建了帖子
2003-12-07 02:01
社区公告
暂无公告