我从一个程序中获取此代码,该程序是为了获取数据并将其导出到excel中,它是在vb6中我不太了解vb6我在vb.net中开始编码可能有人告诉我为什么这不适用于excel 2013它打开然后立即关闭,我不确定为什么。
Sub GetExcel()
Dim MyExcel As Object ' Variable to hold reference
' to Microsoft Word.
Dim ExcelWasNotRunning As Boolean ' Flag for final release.
' Test to see if there is a copy of Microsoft Excel already running.
10 On Error Resume Next ' Defer error trapping.
' Getobject function called without the first argument returns a
' reference to an instance of the application. If the application isn't
' running, an error occurs.
20 Set MyExcel = GetObject(, "XLMAIN")
30 If Err.Number <> 0 Then ExcelWasNotRunning = True
40 Err.Clear ' Clear Err object in case error occurred.
' Check for Microsoft Excel. If Microsoft Excel is running,
' enter it into the Running Object table.
50 DetectExcel
' Set the object variable to reference the file you want to see.
60 Set MyExcel = GetObject(App.Path & "\test.xls")
' Show Microsoft Word through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyWord object reference.
' MyExcel.Application.Visible = True
' MyExcel.document(1).Visible = True
70 MyExcel.Show , f1
'//////////////////////////////////////////////
' Do manipulations of your file here.
'//////////////////////////////////////////////
' ...
' If this copy of Microsoft Excel was not running when you
' started, close it using the Application property's Quit method.
' Note that when you try to quit Microsoft Excel, the
' title bar blinks and a message is displayed asking if you
' want to save any loaded files.
80 If ExcelWasNotRunning = True Then
90 MyExcel.Application.Quit
100 End If
110 Set MyExcel = Nothing ' Release reference to the
' application and spreadsheet.
End Sub
Sub DetectExcel()
' Procedure dectects a running Word and registers it.
Const WM_USER = 1024
Dim hwnd As Long
' If Excel is running this API call returns its handle.
10 hwnd = FindWindow("XLMAIN", 0)
20 If hwnd = 0 Then ' 0 means Word not running.
30 Exit Sub
40 Else
' Word is running so use the SendMessage API
' function to enter it in the Running Object Table.
50 SendMessage hwnd, WM_USER + 18, 0, 0
60 End If
End Sub
即使我可以就如何重写这个问题找到一些方向,我们将不胜感激。
答案 0 :(得分:1)
自从我使用它以来已经很长时间了,所以你可能需要解决一些更好的问题......但是:
首先 - 摆脱On Error Resume Next
它掩盖接下来发生的任何事情。
这不是您想要忽略错误的情况。捕获错误,向用户显示有用的(不是调试信息而不是可用于黑客攻击的细节),然后恢复或返回(清除已分配的对象变量以避免内存泄漏)。< / p>
然后单步执行代码以查看您获得的错误。
可能会有所帮助的一些事情:
将GetObject
中的规格更改为"Excel.Application"
,即
Set MyExcel = GetObject(, "Excel.Application")
使用实际的Excel对象及其方法和属性,而不是支持MyExcel.Show
,而不是MyExcel.Application.Visible = True
,而我对MyExcel.document(1).Visible = True
提出质疑。
查找Excel对象模型帮助以获取详细信息。永远不要硬编码索引 - 获取您想要的实际参考并使用它。
您仍然可以在线找到有关Excel和VB6的文章。使用您选择的搜索引擎并祝您好运。
要小心那些说不可能的事情 - 先看看它是否有效。有人说你可以在64位系统上安装VB6 - 但事实并非如此,但是有一些问题需要它才能运行。有人说你不能从VB6与64位Office进行交互,但事实并非如此。也许你不能做一些事情 - 我没有做太多的事情,只是知道可以做一些事情。
考虑在VB6中使用类型化对象进行开发和测试。它可能非常有用,但要使应用程序版本独立,您需要在最终测试和部署之前删除对象类型。