我有一个包含表单的Excel VBA宏。我希望VB.net隐藏表单或控制它,然后单击“X”按钮或自定义“退出”按钮。
有人有这方面的经验吗?
答案 0 :(得分:2)
Sendkeys非常不可靠。
如果您可以从VB.Net自动化Excel,我会建议。如果您对从VB.Net自动化Excel感兴趣,请参阅this。
如果您不想自动化但希望直接处理它,那么我建议您使用FindWindow
和Sendmessage
API来控制表单。请参阅此示例。
假设Excel中有一个用户表单,如下所示
使用此代码形式VB.Net
<强> CODE 强>:
Imports System.Runtime.InteropServices
Imports System.Text
Public Class Form1
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Msg As UInteger, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function
Private Const WM_CLOSE = &H10
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Ret As Integer
'~~> Get the handle of the Excel Userform named "Example"
Ret = FindWindow(vbNullString, "Example")
'~~> If Found
If Ret <> 0 Then
'~~> Close the Window
SendMessage(Ret, WM_CLOSE, CLng(0), CLng(0))
End If
End Sub
End Class