用VB对EXCEL操作时出现“运行时错误:‘424’要求对象”

2024-12-26 11:06:38
推荐回答(1个)
回答1:

当你第2次点击 Command1_Click a=1 所以并没有执行 Set xl = New Excel.Application
所以才会出错
你可以改为 :
Dim a As Single

Private Sub form_load()
a = 0
Dim xl As Excel.Application
Dim xlbook As Excel.Workbook
Dim xlsheet As Excel.Worksheet
End Sub

Private Sub Command1_Click()
Set xl = New Excel.Application
If a <> 0 Then GoTo nonowbook

With xl
.Workbooks.Add
Set xlbook = .ActiveWorkbook
Set xlsheet = .ActiveSheet
End With

a = a + 1

nonowbook:

With xlsheet
'''这里将我对表格进行些操作
End With

If xl.Visible = True Then
Exit Sub
End If
xl.Visible = True
End Sub