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的时候有时候会报 方法作用于对象失败 的错误 ,一般是在新建帐套第一次向数据库中导入的时候报这个错误,以后就没事了,不知道怎么回事,请大侠们分析一下,谢谢了。

解决方案 »

  1.   

    Cells(2, "B")换成Cells(2, 2)
    Cells的两个参数是数值,不是字符串
      

  2.   

    引用单元格也可以使用range
    Cells(2, 2) 相当于range("B2")
      

  3.   

    Cells(2, "B") 可以吧,我可以读出值来的啊 
      

  4.   

    参数Cells([RowIndex],[ColumnIndex])    出错是在建帐后第一次用Excel导入时执行到那个地方出错 我也很高不清楚 
    执行到  xlSheet.Cells(2, "B").Value时 xlSheet不是Nothing,但是总是报错,忽略过去后,第二次就ok了
      

  5.   

    Dim xlSheet As worksheet
      

  6.   


    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
      

  7.   

    我是把赋值给一个对象的值 ,都是字符串
    oTargetItems.Item(i).Value = xlSheet.Cells(row, oTargetItems.Item(i).Column).Value
      

  8.   

    xlSheet.Cells(row, oTargetItems.Item(i).Column).Value 请确认在赋值前:row 的值在于0 小于 256*256 oTargetItems.Item(i).Column  的值也是一样要判断是否符合EXCEL列的数据.比如说:oTargetItems.Item(i).Column= 0 '这是错误的.
    比如说:oTargetItems.Item(i).Column= "ZZZ" '这也是错误的.比如说:oTargetItems.Item(i).Column= "C" '这才是正确的.
      

  9.   

    是不是第一次打开时Excel的控件没注册上啊 有没有这种可能
      

  10.   

    同意,或者用Set ex = CreateObject("Excel.Application")
    Label1.Caption = ex.Range("b2").Value
      

  11.   

    你的 Test.xls 是由别的程序生成的?
    可能 B2 单元无效或者赋予了一个无效的值。