我试图将文本复制到剪贴板,然后粘贴到excel中,同时保持所有格式。
我发现阻止excel跨多个单元格散布文本并保持格式(如项目符号点等)的唯一方法是将其复制到剪贴板后,直接将其粘贴到公式栏中。
我正在使用Win API来获取编辑栏的句柄。
然后向窗口发送WM_PASTE消息以将剪贴板上的内容粘贴。
然后将WM_SETFOCUS消息发送到准备接收返回键的窗口。
然后发送WM_KEYDOWN消息作为返回键。
Private Declare Function FindWindow _
Lib "user32" _
Alias "FindWindowA" _
(ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx _
Lib "user32" _
Alias "FindWindowExA" _
(ByVal hwndParent As Long, _
ByVal hwndChildAfter As Long, _
ByVal lpszClass As String, _
ByVal lpszWindow As String) As Long
Private Declare Function SendMessage _
Lib "user32.dll" _
Alias "SendMessageA" _
(ByVal hWnd As Long, _
ByVal Msg As Long, _
ByVal wParam As Long, _
ByRef lParam As Any) _
As Long
Declare Function PostMessage _
Lib "user32" _
Alias "PostMessageA" ( _
ByVal hWnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
lParam As Any) As Long
Declare Function SetForegroundWindow _
Lib "user32" _
(ByVal hWnd As Long) As Long
Private Const WM_CUT As Long = &H300
Private Const WM_COPY As Long = &H301
Private Const WM_PASTE As Long = &H302
Private Const WM_CLEAR As Long = &H303
Private Const WM_UNDO As Long = &H304
Private Const WM_KEYDOWN As Long = &H100
Private Const WM_KEYUP As Long = &H101
Private Const VK_F5 As Long = &H74
Private Const VK_RETURN As Long = &HD
Private Const WM_CHAR As Long = &H102
Private Const WM_SETFOCUS As Long = &H7
Private Const WM_KILLFOCUS As Long = &H8
Private Const WM_IME_SETCONTEXT As Long = &H281
Public Sub pasteClipboard()
hwndMain = Application.hWnd: Debug.Print hwndMain
hwndFormulaBar = FindWindowEx(Application.hWnd, ByVal 0&, "EXCEL<", vbNullString): Debug.Print hwndFormulaBar
hwndDesk = FindWindowEx(Application.hWnd, ByVal 0&, "XLDESK", vbNullString): Debug.Print hwndDesk
hwndSheet = FindWindowEx(hwndDesk, ByVal 0&, "EXCEL7", vbNullString): Debug.Print hwndSheet
RetVal = SendMessage(hwndFormulaBar, WM_PASTE, 0, ByVal 0)
Debug.Print SendMessage(hwndFormulaBar, WM_SETFOCUS, 0, 0)
Debug.Print SendMessage(hwndFormulaBar, WM_IME_SETCONTEXT, &H0, &H0)
Debug.Print SendMessage(hwndFormulaBar, WM_KEYDOWN, VK_RETURN, &H0)
End Sub
所有这些工作直到我发送返回键以完成对单元格的编辑后,这才是我想要的。相反,它在文本框中输入了回车符,这很有意义,但不是我想要的结果。
我用Spy ++查看了公式窗口,看着当我在窗口中键入内容并按回车键时会发生什么-当按回车键时,它完成了对单元格的编辑。
我没有在Spy ++中显示的只有两个命令是WM_IME_SETCONTEXT和WM_IME_NOTIFY,但是老实说,我不确定这两个命令是做什么的。
我尝试使用上面的WM_IME_SETCONTEXT,以为在发送返回键之前可能不得不更改它,但结果没有改变。
如果任何人都可以指出正确的方向发送消息,该消息将完成对单元格的编辑(不必是回车键,那只是我的第一个想法),那就太好了。
非常感谢
答案 0 :(得分:0)
感谢您的所有评论。
@Rita Han-MSFT只要焦点不是VBE窗口,那application.SendKeys就可以工作了!