VB6'运行时错误''对象必需'错误

时间:2017-01-12 01:21:39

标签: vb6 runtime-error

我在添加到现有项目之前测试代码。它看起来像这样完美地运行:

Option Explicit

Dim objShell As Object
Dim m_EngineRun As Object

Sub main()

Set objShell = CreateObject("WScript.Shell")
Set m_EngineRun = objShell.Exec("notepad.exe")
Dim objWMIService As Object
Dim colProcessList As Object

MsgBox m_EngineRun.ProcessID

Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where ProcessID = " & m_EngineRun.ProcessID)

If colProcessList.Count = 1 Then
    objShell.run "TASKKILL /F /IM " & m_EngineRun.ProcessID, , True
    MsgBox m_EngineRun.ProcessID & (" terminated")
Else
    MsgBox m_EngineRun.ProcessID & (" does not exist")
End If
End Sub

然后我添加了下面的行,它失败了424错误。

Option Explicit

Dim objShell As Object
Dim m_EngineRun As Object

'Added this line
Dim m_PID As Object

Sub main()

Set objShell = CreateObject("WScript.Shell")
Set m_EngineRun = objShell.Exec("notepad.exe")

'And this line
Set m_PID = m_EngineRun.ProcessID
Dim objWMIService As Object
Dim colProcessList As Object

'And changed this one
MsgBox m_PID

Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where ProcessID = " & m_EngineRun.ProcessID)

If colProcessList.Count = 1 Then
    objShell.run "TASKKILL /F /IM " & m_EngineRun.ProcessID, , True
    MsgBox m_EngineRun.ProcessID & (" terminated")
Else
    MsgBox m_EngineRun.ProcessID & (" does not exist")
End If
End Sub

绝对是Set m_PID = m_EngineRun.ProcessID行是麻烦制造者。

我根本无法找到与我的具体问题有关的答案。我觉得m_PID可能不是一个对象吗?但如果是这样,应该是什么?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

ProcessID不是一个对象;它是一个整数(数字进程ID)。

删除As ObjectSet,然后直接分配:

Dim m_PID
'....
m_PID = m_EngineRun.ProcessID

最好不要假设一切都是对象,因为你遇到的绝大多数事情可能都不是。我开始时不会期望某个对象,除非你知道其他情况,然后在遇到问题时转向尝试对象。<​​/ p>