简体   繁体   中英

Why i am getting type mismatch error when calling macro from vbscript

When i am calling below macro from vbscript why i am getting type mismatch error

Macro in parameter.xlsm

Sub Proc(sParam1 As String, iParam2 As Integer)
MsgBox sParam1 & " is " & iParam2 & " Years Old"
End Sub

VB Script code

Dim objExcel,objWorkbook

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\ExcelFiles\parameter.xlsm")
sParam1 = Inputbox("Enter the first parameter")
iParam2 = Inputbox("Enter the second parameter")
iParam3= CInt(iParam2)

objExcel.Application.Visible = True

objExcel.Application.Run "parameter.xlsm!Proc",sParam1,iParam3
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

In your procedure you are concatenating strings but the second parameter is of type integer. You need to cast to a string first using the CStr() function

Sub Proc(sParam1 As String, iParam2 As Integer)
MsgBox sParam1 & " is " & CStr(iParam2) & " Years Old"
End Sub

Try declaring your variables explicitly in the vbscript... I also used a long in the workbook code out of habit.

Code inside parameter.xlsm:

Option Explicit
Sub Proc(sParam1 As String, iParam2 As Long)
    MsgBox sParam1 & " is " & iParam2 & " Years Old"
End Sub

VBScript code:

Dim objExcel As Object
Dim objWorkbook As Workbook
Dim sParam1 As String
Dim iParam2 As Long, iParam3 As Long

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\ExcelFiles\parameter.xlsm")
sParam1 = InputBox("Enter the first parameter")
iParam2 = InputBox("Enter the second parameter")
iParam3 = CInt(iParam2)

objExcel.Application.Visible = True

objExcel.Application.Run "parameter.xlsm!Proc", sParam1, iParam3
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM