2015-10-15 85 views
-4
  1. 我有一个Excel文件,其中一些单元格值是使用宏动态生成的。
  2. 文件也是只读的。
  3. 我必须阅读这些动态生成的值使用C#代码。 使用以下宏代码生成单元格的值:

**Sub abc() Range("E5").Value = "string" Range("E6").Value = 2 End Sub**如何读取使用c#中的宏动态生成的单元格值?

谢谢......!

+1

纯代码编写请求是题外话堆栈溢出 - 我们期望在这里 问题涉及到具体* *编程问题 - 但我们 会很乐意帮助你自己写!告诉我们 [你试过的东西](http://whathaveyoutried.com),以及你卡在哪里。 这也将帮助我们更好地回答你的问题。 –

回答

0

检查是否需要连接到已打开的excel文件。 如果您使用excelApp.Workbooks.Open,它不会反映由宏更新的工作表数据。 相反,尝试BindToMoniker将方法如下:

private void btnGetXLSValue_Click(object sender, EventArgs e) 
    { 

     object _row = 5; 
     object _column = 5; 
     Excel.Application excelApp = new Excel.Application(); 

     excelApp.Visible = false; 
     excelApp.ScreenUpdating = false; 
     excelApp.DisplayAlerts = false; 
     Microsoft.Office.Interop.Excel.Workbook excelWorkbook ;//= excelApp.Workbooks.Open(@"C:\July.xlsm", 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); 
     //Get a reference to the Workbook object by using a file moniker. 
     //The xls was saved earlier with this file name. 
     excelWorkbook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(@"C:\July.xlsm"); 

     Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets; 
     string currentSheet = "July 2015"; 
     Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(currentSheet); 
     Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)excelWorksheet.UsedRange; 
     string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString(); 
     //string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).get_Value(range).ToString(); 

     MessageBox.Show(sValue); 
    } 
相关问题