请问VB如何提取Excel文件中的数据?

2024-12-04 13:42:36
推荐回答(4个)
回答(1):

做起来太麻烦了。请参阅我的博客:http://hi.baidu.com/zgmg/blog/item/ab8d2dd1888dbcdf572c84bf.html
Private Sub Command1_Click()
If ZID(Text1) = 0 Then
MsgBox "对不起,没找到您输入的ID!"
Else
Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Open("D:\客户资料.xls")
Text2 = xlApp.Worksheets("Sheet1").Range("A1").Cells(ZID(Form1.Text1), 2)
End If
On Error Resume Next
xlBook.Close (True)
xlApp.ActiveWorkbook.Close
xlApp.Quit
Set xlApp = Nothing
Shell "taskkill.exe /im Excel.exe /f", vbHide
End Sub
Function ZID(ID As String) As Integer
Dim I As Integer
Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Open("D:\客户资料.xls")
I = 1
Do
If xlApp.Worksheets("Sheet1").Range("A1").Cells(I, 1) = "" Then
ZID = 0
Exit Function
End If
If xlApp.Worksheets("Sheet1").Range("A1").Cells(I, 1) = Form1.Text1 Then
ZID = I
Exit Do
End If
I = I + 1
Loop
On Error Resume Next
xlBook.Close (True)
xlApp.ActiveWorkbook.Close
xlApp.Quit
Set xlApp = Nothing
End Function
Private Sub Command2_Click()
If ZID(Text1) = 0 Then
MsgBox "对不起,没找到您输入的ID!"
Else
Set xlApp = CreateObject("Excel.Application") '创建EXCEL对象
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Open("D:\客户资料.xls")
xlApp.Worksheets("Sheet1").Range("A1").Cells(ZID(Form1.Text1), 2) = Val(Text2)
xlBook.Save
End If

On Error Resume Next
xlBook.Close (True)
xlApp.ActiveWorkbook.Close
xlApp.Quit
Set xlApp = Nothing
Shell "taskkill.exe /im Excel.exe /f", vbHide
End Sub

回答(2):

Dim a, b, i
Private Sub Command1_Click()
On Error Resume Next
Text2 = "": i = 0
'如果不是第一个你可以把下面的Sheets("sheet1")改为相应的表
i = b.sheets("sheet1").Range("a:a").Find(What:=Text1, LookAt:=1).Row
Text2 = b.sheets("sheet1").cells(i, 2)

End Sub

Private Sub Command2_Click()
b.sheets("sheet1").cells(i, 2) = Text2
End Sub

Private Sub Form_Load()
Set a = CreateObject("Excel.Application")
Set b = a.Workbooks.Open("d:\q1.xls") '这里改为你的EXCEL文件的路径及文件全名
End Sub

Private Sub Form_Unload(Cancel As Integer)
b.Close 1
End Sub

说明:因为要提取的数据量不大,因此可以用这种方法.
由于这种操作的效率是很低的,不能采取循环的方法来查找匹配的单元格,本程序采用了FIND方法(全字匹配)来检索,因此,本程序的效率是没有问题的.

如果需要大量提取数据,建议用数据库的访问方式

回答(3):

使用OLE控件

回答(4):

Ctrl+H