본문 바로가기
프로그래밍/C#

[C#] C#에서 VBA 코드 실행하고 argument 전달 및 결과값 리턴받기

by 왕초보 개발자 2021. 3. 25.
728x90

// 엑셀 객체 생성
Microsoft.Office.Interop.Excel.Application excel 
 = new Microsoft.Office.Interop.Excel.Application();

// 엑셀 실행 옵션 지정
excel.DisplayAlerts = false;   // 엑셀 알림창 띄우기 옵션
excel.Visible = true;          // 매크로 실행 중 엑셀 화면 보이기 옵션

// 매크로 엑셀 파일 열기
Microsoft.Office.Interop.Excel.Workbook ExcelWorkBook 
 = excel.Workbooks._Open(@"C:\Users\gudfo\Desktop\macroFile.xlsm");

// 엑셀 매크로 실행 - 매크로 이름 뒤에 순차적으로 Arguments 입력
var result = excel.Run("macroName", "arg1", "arg2");

// 엑셀 함수의 리턴값 가져오기
String macro_Result = result.ToString();

// 엑셀 파일 저장
ExcelWorkBook.Save();
// 엑셀 종료
ExcelWorkBook.Close(false);
excel.Quit();

728x90