Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long 
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Long) As Long Sub test() 
  Window = FindWindow(vbNullString, "无标题 - 记事本") ''程序运行正常,能找到句柄983414 
  hwnd = FindWindow("XLMAIN", Application.Caption)   Window = SetForegroundWindow(Window) 
  Sleep (2000) 
  Windowss = SetForegroundWindow(hwnd) 
End Sub 这个程序能在excel与记事本之间相互,切换。
但用for ... next 就出问题了。
好像SetForegroundWindow引用有问题,【说明】
  将窗口设为系统的前台窗口。这个函数可用于改变用户目前正在操作的应用程序 
【返回值】
  Long,非零表示成功,零表示失败。会设置GetLastError 
【其它】
  不应随便使用它,因为一旦程序突然从后台进入前台,可能会使用户产生迷惑
【参数表】
  hwnd -----------  Long,带到前台的窗口请问各位大侠,
这个程序能在excel与记事本之间相互切换,不用SetForegroundWindow,还有什么语句可用,谢谢。

解决方案 »

  1.   

    SetForegroundWindow可以的。是你的程序的问题。
      

  2.   

    SetForegroundWindow,总是将窗口置前,目标是记事本运行完后,要极小化,excel置前。
    置前、极小化循环再能体现效果。
    请试一下,你就知道结果。
    Sub test() 
      Window = FindWindow(vbNullString, "无标题 - 记事本") ''程序运行正常,能找到句柄983414 
      hwnd = FindWindow("XLMAIN", Application.Caption)   Window = SetForegroundWindow(Window) 
      Sleep (2000) 
      Windowss = SetForegroundWindow(hwnd) 
    End Sub