Calling vba function(with parameters) from vbscript and show the result

巧了我就是萌 提交于 2021-01-28 13:00:32

问题


I have the following vba function ( in a module in Excel file)

Public Function validate_fncname(strFncname As String) As Boolean
.
.
.
validate_fncname  = True
End Function

and I wrote the following vbscript to call it :

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook =  objExcel.Workbooks.Open("C:\Users\uidu8611\Desktop\CAM0500040F10_SW_Quality_Assurance_Report_Template(new_version).xlsm")

objExcel.Application.Visible = True

Dim str
str ="hello"

Dim validate_fncname 

 validate_fncname =  objExcel.Application.Run("'C:\Users\uidu8611\Desktop\CAM0500040F10_SW_Quality_Assurance_Report_Template(new_version).xlsm'!validate_fncname", str)

Wscript.Echo validate_fncname

however when I run the script, it gives me type mismatch error for the line:

objExcel.Application.Run("'C:\Users\uidu8611\Desktop\CAM0500040F10_SW_Quality_Assurance_Report_Template(new_version).xlsm'!validate_fncname", str)

Despite the fact that the type is correct (String)

furthermore if I change it to :

objExcel.Application.Run("'C:\Users\uidu8611\Desktop\CAM0500040F10_SW_Quality_Assurance_Report_Template(new_version).xlsm'!validate_fncname(5)")

It doesn't give me an error, although 5 is integer!

Where is my mistake please?


回答1:


You already have your validate_fncname method, which looks fine (except setting the return value to True should probably be done in an if then statement to avoid setting everything to True).

When calling this function, you should just be able to do the following:

Dim validateResult As Boolean
Dim str as String
str = "hello"
validateResult = validate_fncname(str)
Debug.Print validateResult



回答2:


I played with this for a while and came up with the same error.
In my case I was just trying to pass a string back and forth.

Then I looked up the dim statement for VBScript and it says "All VBScript variables are variants" so I changed the function on the spreadsheet to as Variant and that worked for me. Hope this helps others that come across this thread.



来源:https://stackoverflow.com/questions/13232615/calling-vba-functionwith-parameters-from-vbscript-and-show-the-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!