首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyDown in WebBrowser (Excel )

KeyDown in WebBrowser (Excel )
EN

Stack Overflow用户
提问于 2022-03-11 22:43:13
回答 1查看 266关注 0票数 0

如果在WebBrowser中使用UserForm,是否有方法知道按下了什么键?

(预先谢谢:)

编辑:我基本上想在KeyDown上打开一个不同的WebBrowser,但是WebBrowser阻止了这一点。也许我可以从UserForm上运行WebBrowser的一个子程序。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-13 01:40:18

下面是一个非常基本的示例,显示您可以从VBA向HTML页面发送消息,然后向另一个方向发送消息:

UserForm:

代码语言:javascript
复制
Option Explicit

Dim obj As webEvents 'must be Global to remain in scope...

'send a message to the browser page
Private Sub CommandButton1_Click()
    'would need to escape the text sent if it contains (eg) '
    Me.WebBrowser1.Document.parentWindow.execScript "MessageIn('" & Me.TextBox1.Text & "')"
End Sub

'receive a message from the browser page
Public Sub HandleBrowserMessage(s As String)
    MsgBox "From web:" & vbLf & s
End Sub

Private Sub UserForm_Initialize()
    Me.WebBrowser1.Navigate "about:blank"  'load a blank document
    Application.Wait Now + TimeSerial(0, 0, 1)
    With Me.WebBrowser1.Document 'load some HTML
        .Open "text/html"
        .write Sheet1.Range("A1").Value
        .Close
    End With
    
    Set obj = New webEvents                  'new class instance
    Set obj.ParentForm = Me                  'for the callback
    Set obj.HtmlOutput = Me.WebBrowser1.Document.getElementById("msgOut")
End Sub

类模块webEvents

代码语言:javascript
复制
Option Explicit

Public ParentForm As Object 'not As userform!
Public WithEvents HtmlOutput As MSHTML.HTMLInputElement

'handling click since change seems unreliable
Private Function HtmlOutput_onclick() As Boolean
    ParentForm.HandleBrowserMessage CStr(HtmlOutput.Value)
End Function

单元格A1中的HTML:

代码语言:javascript
复制
<html><body>
<input type="hidden" id="msgOut" /><br>
To VBA: <input type="text" size="20" id="msg" />
<button  onclick="MessageOut()">Send to VBA</button><br><br>
From VBA: <span id="showMessage" style="color:#F00"></span><br>
<script>
function MessageIn(s){  document.getElementById("showMessage").innerText = s;  }
function MessageOut(s){  
    var el = document.getElementById("msgOut");
    el.value = document.getElementById("msg").value; 
    el.click();
}
</script>
</body></html>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71445388

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档