簡體   English   中英

為什么從vbscript調用宏時出現類型不匹配錯誤

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

當我從vbscript調用下面的宏時,為什么我遇到類型不匹配錯誤

parameter.xlsm中的宏

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

VB腳本代碼

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

在您的過程中,您正在連接字符串,但是第二個參數是整數類型。 您需要先使用CStr()函數將其轉換為字符串

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

嘗試在vbscript中顯式聲明您的變量...我也習慣了在工作簿代碼中使用很long

parameter.xlsm中的代碼:

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

VBScript代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM