首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VB >

哪位高手能帮小弟我精减一下这段代码,不是很长。如果你能做一下注释更好,多谢

2012-01-15 
谁能帮我精减一下这段代码,不是很长。如果你能做一下注释更好,谢谢!PrivateSubCommand1_Click()CommonDialo

谁能帮我精减一下这段代码,不是很长。如果你能做一下注释更好,谢谢!
Private   Sub   Command1_Click()
CommonDialog1.Filter   =   "Excel文件(*.xls)|*.xls "
CommonDialog1.ShowOpen
If   CommonDialog1.FileName   =   " "   Then   Exit   Sub
On   Error   Resume   Next
Dim   xlApp   As   New   Excel.Application   '定义并创建EXCEL对象
Dim   xlBook   As   Excel.Workbook   '创建工作簿
Dim   xlSheet   As   Excel.Worksheet
xlApp.Visible   =   flase   '让Excel可见
On   Error   GoTo   openErr
Set   xlBook   =   xlApp.Workbooks.Open(CommonDialog1.FileName)     '打开Excel文件
MsgBox   xlApp.Sheets( "Sheet1 ").Cells(3,   1)   '读取第一个单元格的内容
'xlApp.Quit     '关闭Excel
Set   xlBook   =   Nothing
Set   xlApp   =   Nothing
Exit   Sub
openErr:
Set   xlBook   =   Nothing
Set   xlApp   =   Nothing
MsgBox   Err.Description
End   Sub


[解决办法]
代码已作修改:

Option Explicit
Dim xlapp As Variant
Dim xlBook As Variant
Dim xlSheet As Variant

Private Sub Command1_Click()
CommonDialog1.Filter = "Excel文件(*.xls)|*.xls "
CommonDialog1.ShowOpen
If CommonDialog1.FileName <> " " Then
On Error GoTo openErr
Set xlapp = CreateObject( "excel.application ")
xlapp.Visible = True
Set xlBook = xlapp.Workbooks.Add
Set xlSheet = xlBook.worksheets(1)
Set xlBook = xlapp.Workbooks.Open(CommonDialog1.FileName) '打开Excel文件
Form1.Show
MsgBox xlapp.Sheets( "Sheet1 ").Cells(1, 1) '读取Sheet1第一个单元格的内容
MsgBox ( "关闭Excel ")
xlapp.Quit '关闭Excel
End If
Exit Sub
openErr:
Set xlBook = Nothing
Set xlapp = Nothing
MsgBox Err.Description
Resume Next
End Sub

[解决办法]
已经很精简了。楼主也可以试试ADODB+SQL:

Private Sub Command1_Click()
CommonDialog1.Filter = "Excel文件(*.xls)|*.xls "
CommonDialog1.ShowOpen
If CommonDialog1.FileName = " " Then Exit Sub
With CreateObject( "ADODB.Connection ")
.Open "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties= 'Excel 8.0;HDR=NO; ';Data Source= " & CommonDialog1.FileName
MsgBox .Execute( "Select * from [Sheet1$A3] ").fields(0).Value
.Close
End With
End Sub

热点排行