在方法C#中使用函数中的variables
我做了一个函数来打开Excel,打开工作簿,然后将某个工作表设置为活动状态(取决于用户input)。 function…
public void openExcel() { var excelObj = new Microsoft.Office.Interop.Excel.Application(); string fileName = @"C:\Users\" + userName + @"\Documents\Visual Studio 2015\Projects\ProgramForMom\ProgramForMom\bin\Debug\Excel Files\" + frm2.year.Text + " Expenses"; Workbook wb = excelObj.Workbooks.Open(fileName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); wb.Activate(); Microsoft.Office.Interop.Excel.Worksheet ws = wb.Worksheets[frm2.month.Text]; ws.Activate(); }
我有另一种方法,我想在工作表上select范围…
var cellValue = ws.Range["A10"].Value2;
我得到以下错误:
“在当前的情况下,名字'ws'不存在”
我试着看这个MSDN页面,但很难理解它(我是编程新手) – https://msdn.microsoft.com/en-us/library/ms173114.aspx
我有大约5种不同的方法(基于用户在Windows窗体中单击不同的button的时间),在每种方法中,我想以相同的方式打开Excel,但是select不同的范围。 除了重写5次,还有什么办法吗?
任何帮助将非常感激。
您可以轻松使用现有的方法。 只要让它返回打开的工作表:
public Worksheet openExcel() { var excelObj = new Microsoft.Office.Interop.Excel.Application(); string fileName = @"C:\Users\" + userName + @"\Documents\Visual Studio 2015\Projects\ProgramForMom\ProgramForMom\bin\Debug\Excel Files\" + frm2.year.Text + " Expenses"; Workbook wb = excelObj.Workbooks.Open(fileName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); wb.Activate(); Microsoft.Office.Interop.Excel.Worksheet ws = wb.Worksheets[frm2.month.Text]; ws.Activate(); return ws; // return the activated Worksheet }
然后你可以在其他方法中使用对ws
的引用:
public void SomeMainMethod() { // open the worksheet Worksheet ws = openExcel(); // and use it anywhere // invoke your other method(s) and provide the reference to 'ws' YourOtherMethod(ws); }
您不能在另一个函数中使用一个函数的variables。
你在openExcel
函数中声明了ws
variables,所以你可以在那里使用它,如果你想在另一个函数中使用它,你必须在第二个函数中声明。
Microsoft.Office.Interop.Excel.Worksheet ws = wb.Worksheets[frm2.month.Text]; var cellValue = ws.Range["A10"].Value2;
或者,你可以在课堂内但是在function之外将ws
作为一个全球variables来表示,然后在这个课程的所有function中都可以被访问和认可。