vb excel操作出错
下面是我从我的另外一个帖子中拷过来的,想引起更多人帮忙,所以另发新帖,请各位帮忙看下,谢谢啦!
是对一个excel中多行进行sum出错
引用 2 楼 king06 的回复:
VB code
Range("A1:A101").Select
Range("A101").Activate
ActiveCell.FormulaR1C1 = "=SUM(R[-100]C:R[-1]C)" '第101行记录这个和是多少.
我使用的是这位同学的方法,但是现在遇到另外一个问题
我的程序重复运行时报错 object variable or with block variable not set
报错行是 ActiveCell.FormulaR1C1 = "=SUM(R[-50]C:R[-1]C)" 报错对象是ActiveCell.FormulaR1C1
下面是我的对Excel操作的代码,麻烦各位给看一下,问题处在哪,谢谢!
--定义
Dim excelApp As Excel.Application
Dim excelBook As Excel.Workbook
Dim excelSheet As Excel.Worksheet
--打开Excel对象
Set excelApp = CreateObject("Excel.Application")
Set excelBook = excelApp.Workbooks.Open(excelPath)
Set excelSheet = excelBook.Worksheets(1)
--对excel的操作等
excelSheet.Cells(endRow, 1) = "汇总:"
excelSheet.Range("C5:C" & endRow).Select
excelSheet.Range("C" & endRow).Activate
ActiveCell.FormulaR1C1 = "=SUM(R[-50]C:R[-1]C)"
--对excel的关闭等操作
excelApp.Visible = True
excelBook.SaveAs savePath
excelBook.Save
Set excelApp = Nothing
Set excelBook = Nothing
Set excelSheet = Nothing
当程序重复执行时,就会报错,请各位帮忙看下是怎么回事,急呀,谢谢啦!!!
[解决办法]
错误语句:
ActiveCell.FormulaR1C1 = "=SUM(R[-50]C:R[-1]C)"
正确语句:
excelApp.ActiveCell.FormulaR1C1 = "=SUM(R[-50]C:R[-1]C)"
也就是加上excelApp
[解决办法]
你的程序还有很多问题,参照以下程序去改吧。
Private Sub Command1_Click()'引用了excel 11.0'--定义:注意关键字new创建excel新实例' :去掉CreateObject.......语句,' :引用了excel 11.0就不要再用这' :个语句建立实例。 Dim excelApp As New Excel.Application Dim excelBook As New Excel.Workbook Dim excelSheet As New Excel.Worksheet Dim excelPath As String '给出文件路径 excelPath = "c:\123.xls" ' --打开Excel对象 Set excelBook = excelApp.Workbooks.Open(excelPath) Set excelSheet = excelBook.Worksheets(1) 'excelApp.Visible = True '愿意显示可以在这里显示'--对excel的操作等 If excelSheet.Cells(excelSheet.Cells.SpecialCells(11).Row, 1) = "汇总:" Then Else excelSheet.Cells(excelSheet.Cells.SpecialCells(11).Row + 1, 1) = "汇总:" End If excelSheet.Range("C" & excelSheet.Cells.SpecialCells(11).Row).Activate excelApp.ActiveCell.FormulaR1C1 = "=SUM(R[" & 5 - excelSheet.Cells.SpecialCells(11).Row & "]C:R[-1]C)"' --对excel的关闭等操作 excelBook.Save excelApp.Quit '这里一定要退出excel,否则内存中会有很的excel实例,运行一次增加一个。 Set excelApp = Nothing Set excelBook = Nothing Set excelSheet = NothingEnd Sub