Dim xlApp As Object 'Excel 应用程序
Dim xlBook As Object
Dim xlSheet As Object
Dim cFilePath As String '文件路径
Set xlApp = CreateObject("Excel.Application")
cFilePath = "C:\Test.xls"
Set xlBook = xlApp.Workbooks.Open(cFilePath, , True)
xlApp.Visible = False
Set xlSheet = xlBook.Sheets(1)
xlSheet.Activate
Label1.Caption = xlSheet.Cells(2, "B").Value
xlBook.Close False
xlApp.quit
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing我的程序大概就是这样的 ,只不过是动态的读取某行列的值导入到数据库 ,路径也是也是随意打开的Excel文件路径,但是在执行到 xlSheet.Cells(2, "B").Value的时候有时候会报 方法作用于对象失败 的错误 ,一般是在新建帐套第一次向数据库中导入的时候报这个错误,以后就没事了,不知道怎么回事,请大侠们分析一下,谢谢了。
Dim xlBook As Object
Dim xlSheet As Object
Dim cFilePath As String '文件路径
Set xlApp = CreateObject("Excel.Application")
cFilePath = "C:\Test.xls"
Set xlBook = xlApp.Workbooks.Open(cFilePath, , True)
xlApp.Visible = False
Set xlSheet = xlBook.Sheets(1)
xlSheet.Activate
Label1.Caption = xlSheet.Cells(2, "B").Value
xlBook.Close False
xlApp.quit
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing我的程序大概就是这样的 ,只不过是动态的读取某行列的值导入到数据库 ,路径也是也是随意打开的Excel文件路径,但是在执行到 xlSheet.Cells(2, "B").Value的时候有时候会报 方法作用于对象失败 的错误 ,一般是在新建帐套第一次向数据库中导入的时候报这个错误,以后就没事了,不知道怎么回事,请大侠们分析一下,谢谢了。
Cells的两个参数是数值,不是字符串
Cells(2, 2) 相当于range("B2")
执行到 xlSheet.Cells(2, "B").Value时 xlSheet不是Nothing,但是总是报错,忽略过去后,第二次就ok了
Option ExplicitPrivate Sub Command1_Click()
Dim xlApp As Object 'Excel 应用程序
Dim xlBook As Object
Dim xlSheet As Object
Dim cFilePath As String '文件路径
Set xlApp = CreateObject("Excel.Application")
cFilePath = "C:\Test.xls"
Set xlBook = xlApp.Workbooks.Open(cFilePath, , True)
xlApp.Visible = False
Set xlSheet = xlBook.Sheets(1)
xlSheet.Activate
Label1.Caption = xlSheet.Cells(2, "B").Text '(此处我改为Value,与Text都没有产生错误,)
'(请确认是否赋值给数据库时产生的问题.因你示例中是放入Label1.Caption)
xlBook.Close False
xlApp.quit
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = NothingEnd Sub
oTargetItems.Item(i).Value = xlSheet.Cells(row, oTargetItems.Item(i).Column).Value
比如说:oTargetItems.Item(i).Column= "ZZZ" '这也是错误的.比如说:oTargetItems.Item(i).Column= "C" '这才是正确的.
Label1.Caption = ex.Range("b2").Value
可能 B2 单元无效或者赋予了一个无效的值。