将按钮按下的VBA响应发送到C#

时间:2018-02-08 21:41:03

标签: c# excel vba

我有一个C#程序,它调用这样的Excel宏:

private void _xlCall_Click(object sender, EventArgs e)  
{  
            Excels.Application oExcel = new Excels.Application();  
            Excels.Workbooks oBooks = oExcel.Workbooks;  
            string tabName=cbSelectTable.Text;  
            object oMissing = System.Reflection.Missing.Value;  
            Excels._Workbook oBook = null;  
            oExcel.Visible = false;  
string srcPath = "C:\\Desktop\\file.xlsm";  
oBook = oBooks.Open(srcPath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);  
string fNames;  
                fNames = oExcel.Run(tabName);  
                oExcel.Visible = true;  
} 

Excel宏有一个代码,用于执行某些格式化,然后询问用户是否

  

他们想要在不查看数据的情况下更新sql,或者他们想要更新   首先看数据?

VBA代码是这样的:

Sub checkDat(string tableN)  
//Update Code here  
.  
.  
.  
Dim Msg, Style, Title, Help, Ctxt, Response, MyString  
Msg = "Do you want to insert the data to sql without viewing? "  
Style = vbYesNo     
Response = MsgBox(Msg, Style)  
Dim fkCntrl As IRibbonControl  
If Response = vbYes Then   
   XL2SQLInserts fkCntrl  
Else   
   MsgBox ("Data was not Inserted")   
End If  

Exit Sub  
error_wsconsol:  
MsgBox (Err.Source & ": The following error occured  " & Err.Description)  
End Sub

问题:
我希望只有在用户单击“是”时才打开Excel工作簿。

关于如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:0)

我能够在这里评论的人的帮助下修复它。 我把Sub改成了这样的功能:

Function checkDat() as String  
//Update Code here  
.  
.  
.  
Dim Msg, Style, Title, Help, Ctxt, Response, MyString  
Msg = "Do you want to insert the data to sql without viewing? "  
Style = vbYesNo     
Response = MsgBox(Msg, Style)  
Dim fkCntrl As IRibbonControl  
If Response = vbYes Then   
   XL2SQLInserts fkCntrl
checkDat="Yes"  
Else   
   MsgBox ("Data was not Inserted")   
checkDat="No"
End If  

Exit Function
error_wsconsol:  
MsgBox (Err.Source & ": The following error occured  " & Err.Description)  
End Function 

C#代码是这样的:

private void _xlCall_Click(object sender, EventArgs e)  
{  
            Excels.Application oExcel = new Excels.Application();  
            Excels.Workbooks oBooks = oExcel.Workbooks;  
            string tabName=cbSelectTable.Text;  
            object oMissing = System.Reflection.Missing.Value;  
            Excels._Workbook oBook = null;  
            oExcel.Visible = false;  
string srcPath = "C:\\Desktop\\file.xlsm";  
oBook = oBooks.Open(srcPath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);  
string fNames;  
                fNames = oExcel.Run(tabName); //fNames is going to get the value   
if(fNames=="Yes")  
{  
                oExcel.Visible = true;    
}  
else  
{  
}  
}