操作excel,第一次运行可以,第二次运行为什么报错?

humdark 2004-11-23 11:34:19
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open(txtFile.Text)
Set xlSheet = xlBook.Sheets(1)

xlSheet.Range("A1:J1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.MergeCells = True
End With

xlApp.Visible = True

Set xlApp = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open(txtFile.Text)
Set xlSheet = xlBook.Sheets(1)

xlSheet.Range("A1:J1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.MergeCells = True
End With

运行到第二个 With Selection
.HorizontalAlignment = xlCenter
时报错:实时错误“91”,对象变量或with块变量未设置
其中 第二个Selection=nothing
...全文
235 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
shanlisong 2004-11-26
  • 打赏
  • 举报
回复
你把xlBook 和xlSheet 在用第二个时候都Nothing了,所以在用第二个之前必需在
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
leolan 2004-11-26
  • 打赏
  • 举报
回复
試試 xlApp.Selection
humdark 2004-11-26
  • 打赏
  • 举报
回复
leolan(史留香) :
xlSheet.Selection 报错 未找到方法或数据成员
haohaohappy 2004-11-26
  • 打赏
  • 举报
回复
你没有完全关闭EXCEL,在进程中你还可以看到的。应该:
xlBook.Close
Set xlBook = Nothing
xlApp.Quit
Set xlSheet = Nothing
Set xlApp = Nothing
humdark 2004-11-23
  • 打赏
  • 举报
回复
实际程序中我不希望关闭excel
因为要由用户预览后选择是否打印
humdark 2004-11-23
  • 打赏
  • 举报
回复
能说一下是什么原因吗?
jam021 2004-11-23
  • 打赏
  • 举报
回复
xlBook.Close
Set xlBook = Nothing
xlApp.Quit
Set xlSheet = Nothing
Set xlApp = Nothing
gg137zeus 2004-11-23
  • 打赏
  • 举报
回复
up
aiur2000 2004-11-23
  • 打赏
  • 举报
回复
眼误,那几句没问题。
aiur2000 2004-11-23
  • 打赏
  • 举报
回复
Set xlApp = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing
都关闭excell了
creazyfish 2004-11-23
  • 打赏
  • 举报
回复
同意楼上的
leolan 2004-11-23
  • 打赏
  • 举报
回复
With Selection --> With xlSheet.Selection

2,461

社区成员

发帖
与我相关
我的任务
社区描述
VBA(Visual Basic for Applications)是Visual Basic的一种宏语言,是在其桌面应用程序中执行通用的自动化(OLE)任务的编程语言。
社区管理员
  • VBA
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧