JavaScript 调用带有参数的 VBA 例程

JavaScript to call a VBA routine with parameters

本文关键字:VBA 例程 参数 调用 JavaScript      更新时间:2023-09-26
  1. 我需要将参数从HTA的JavaScript传递给Excel VBA代码。

    1. 我可以成功调用VBA函数,但无法正确传递字符串参数。
    2. JavaScript 函数可以传递不同的字符串参数。
    3. 下面是简单和演示形式的代码。
    4. Excel-VBA代码

    Sub subTest(strName As String)
    MsgBox strName
    End Sub
    

HTA code with Javascript

<!DOCTYPE html>
<html>
<head>
<title>HTA</title>
<hta:application 
id="oHta"
applicationname="htaNavi"
border="1"
borderstyle = normal
contextmenu = "yes"
caption="Navigator"
sysmenu="yes"
WINDOWSTATE="maximize"
>
</head>
<body>
<input type="button" value="testing" onclick="funRun('testng string')" />
<input type="button" value="testing second" onclick="funRun('testng')" />
</body>
<script>
var objExl;
var objWb;
var objExl =new ActiveXObject("Excel.Application");
objExl.Visible = true;
var objWb = objExl.Workbooks;
var strpath = ''path'testing_excel_web.xls';
objWb.Open(strpath);
function funRun(strName)
{
alert(strName);
objWb.Application.Run('testing_excel_web.xls!subTest(strName)');
}
</script>
</html>

我可以调用 subTest,但消息框将 strName 填充为字符串,但不将"测试字符串"填充为文本。

我想你想要:

objWb.Application.Run('testing_excel_web.xls!subTest("' + strName + '")');

这样,变量strName的值将连接到您尝试运行的命令。

我对 VBA 函数的这种调用一无所知,所以我不确定您是否需要像我提供的那样围绕strName "

此外,为了安全起见,如果您的strName值包含 " ,您应该使用它:

objWb.Application.Run('testing_excel_web.xls!subTest("' + strName.replace(/"/g, "'"") + '")');

希望有了这个,strName的价值可以是

The word "testing" here
or
"Here's a quote"

它仍然有效。

关键是如果字符串包含",Javascript将/可能会失败。如果它绝对不会包含",那就算了。但我认为这是必要的,因为 strName 值中的任何"都会破坏它作为参数的传递。