一.C#部分:
1.需要引用的庫:
using Microsoft.Office.Interop.Excel
2.C#中新建excel對象:
using Excel=Microsoft.Office.Interop.Excel;
Excel.Application xapp=new Excel.Application();
//打開vba程序所在的excel
string path=@“C:\User\Desktop\test.xlsm”;
Excel.Workbook wb=xapp.Workbooks.Open(path);
//下一步直接可以運(yùn)行“test.xlsm"中的宏了,如果這個宏名為”test",直接這樣就可以:
xapp.Run(“test”)
完整代碼:
` string path = @“C:\Users\Nesus\Desktop\test.xlsm”;
Excel.Application xapp=new Excel.Application();
Excel.Workbook wb=xapp.Workbooks.Open(path);
xapp.Run(“test”);
如果要傳遞C#中的參數(shù)到VBA中,只需要在xapp.Run中加一個參數(shù)就行了,
比如,要傳遞一個字符串s進(jìn)去:
string s=“student”;
xapp.Run(“test”, s);
那么在運(yùn)行VBA程序時,就會引用s。文章來源:http://www.zghlxwxcb.cn/news/detail-503341.html
二.VBA部分
1.不需要傳遞參數(shù)的情況:
Sub test
msgbox(“test”)
End Sub
2.需要傳遞參數(shù)進(jìn)去:
Sub test(Byval stu as string)
msgbox(“test” & stu)
End sub
在運(yùn)行C#代碼xapp.Run(“test”, s)時,會定位到這個叫“test"的宏,然后引用 s="student"的這個字符串,最終輸出 “test student"的結(jié)果。文章來源地址http://www.zghlxwxcb.cn/news/detail-503341.html
到了這里,關(guān)于C#調(diào)用vba程序以及傳遞C#中參數(shù)到VBA程序的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!