vb 数据怎么写入excel?

2025-01-08 08:12:17
推荐回答(2个)
回答1:

'在工程中添加对Excel的引用

Dim xlsApp As Excel.Application

Dim xlsBook As Excel.Workbook

Private Sub Command1_Click()

Dim I As Integer

Set xlsApp = Excel.Application

xlsApp.Visible = False

Set xlsBook = xlsApp.Workbooks.Open("D:\11.xls")

I = 1

Do While xlsApp.Sheets(1).cells(I, 1) <> ""

I = I + 1

Loop

xlsApp.Sheets(1).cells(I, 1) = Text1.Text

xlsBook.Close (True)

xlsApp.Quit

Set xlsApp = Nothing

MsgBox "数据写入成功!"

End Sub

方法一:可以试着用VB书写一段调用SQL Server数据库DTS的代码,然后就可以像直接使用DTS进行数据导入一样就行Excel与SQL Server数据之间的迁移了。

方法二:可以用VB来操作EXCEL,然后一条数据一条数据的插入到数据库中,这种方法不推荐使用,因为VB操作EXCEL是非常慢的,如果数据量太大,很有可能会造成机。

回答2:

'先在工程中引用Microsoft Excel 11.0 Object Library
Private Sub Command1_Click()
On Error Resume Next
Dim objExcel As Excel.Application
Dim objWorkBook As Excel.Workbook
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Add()
objExcel.Visible = True

'设置活动工作表
Dim objSheet As Excel.Worksheet
Set objSheet = objExcel.Worksheets("sheet1")

objSheet.Cells(1, 1) = Text1.text '给1行1列的单元格赋值

objSheet.Cells(1, 2) = Text2.text '给1行2列的单元格赋值
'以上2行如果能用循环语句+数组会更好用,你根据实际具体编写吧

objWorkBook.SaveAs App.Path & "\" & Time & ".xls" '保存在本目录下,文件名为当前时间
objWorkBook.Close
objExcel.Quit
Set objSheet = Nothing
Set objWorkBook = Nothing
Set objExcel = Nothing
End Sub