| 分類:[C#]
・使用言語:C# ・使用ソフト:Visual Studio 2008 Pro ・内容:C#でExcelに接続後、フォームにあるボタンをクリックするとExcelシートに入力されている一番最後の行数を取得したい。
内容は先にした通りでございます。色々調べ、何とか取得できたのですが、もっと分かりやすい方法がありましたら教えてください。 *今回やりたいことは、VBAで言うところの MsgBox SheetName.Cells(65563, 1).End(xlUp).Row です。
・現在のコード using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button2_Click_1(object sender, EventArgs e) { //Excel接続の各変数設定 string ExcelFile; Excel.Application ExcelApp; Excel.Workbook wb; Excel.Worksheet ws; Excel.Range rng;
//接続開始 ExcelFile = @"D:\test2.xls"; ExcelApp = new Excel.Application(); ExcelApp.Visible = false; wb = ExcelApp.Workbooks.Open(ExcelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ws = (Excel.Worksheet)wb.Sheets[1]; ws.Select(Type.Missing); //★★問題の箇所★★現在のところ下記の2行で、値が入力されている最終行が取得できています。 rng = ws.get_Range("A65536", ExcelApp.ActiveCell.get_End(Excel.XlDirection.xlUp)); MessageBox.Show("最大Rowは" + (65536 - rng.Rows.Count + 1).ToString()); wb.Close(false, Type.Missing, Type.Missing); ExcelApp.Quit(); } } }
よろしくお願いいたします。 |