crzzx 发表于 2008-7-8 20:05

急求VB编程进行数据采集保存在EXCEL2003中的问题

请问如何在一个程序中多次调用同一个Excel文件,比如用Timer1控件每隔一定时间把数据保存进入Excel文件里面.下面是我编的一个程序;
Dim exApp  As Excel.Application
Dim i, k As Integer
Private Sub Command1_Click()
     CommonDialog1.ShowOpen
      If Len(CommonDialog1.FileName) >= 1 Then
    exApp.Workbooks.Open CommonDialog1.FileName
    For i = 1 To 5
    Range(Cells(i, 1), Cells(i, 1)) = "aa"
   Range(Cells(i, 2), Cells(i, 2)) = "aa"
   Range(Cells(i, 3), Cells(i, 3)) = "aa"
   Range(Cells(i, 4), Cells(i, 4)) = "aa"
     Next
    exApp.ActiveWorkbook.Save
    exApp.ActiveWorkbook.Close
      End If
   exApp.Quit
   Set exApp = Nothing
   Timer1.Enabled = True
   Timer1.Interval = 3000
End Sub

Private Sub Form_Load()
Set exApp = New Excel.Application
End Sub

Private Sub Timer1_Timer()
    k = k + 1
    CommonDialog1.ShowOpen
If Len(CommonDialog1.FileName) >= 1 Then
[color=Magenta][u] exApp.Workbooks.Open CommonDialog1.FileName[/u]   出错处[/color]   
  Range(Cells(k, 6), Cells(k, 6)) = k
   Range(Cells(k, 7), Cells(k, 7)) = k
   Range(Cells(k, 8), Cells(k, 8)) = k
   Range(Cells(k, 9), Cells(k, 9)) = k
    exApp.ActiveWorkbook.Save
    exApp.ActiveWorkbook.Close
      End If
   exApp.Quit
   Set exApp = Nothing
End Sub
但是一进入Private Sub Timer1_Timer()这个里面运行到 exApp.Workbooks.Open CommonDialog1.FileName时就显示
实时错误'91',对象变量或With快变量未设置。

[[it] 本帖最后由 crzzx 于 2008-7-8 20:57 编辑 [/it]]

[[it] 本帖最后由 crzzx 于 2008-7-8 20:58 编辑 [/it]]

multiple1902 发表于 2008-7-8 21:23

Set exApp = Nothing

第一次timer的时候exApp都成Nothing了,下一次哪里来的Workbooks?

crzzx 发表于 2008-7-10 08:40

谢谢,明白了!

页: [1]

编程论坛