使用 vb.net 在 Excel 工作表中选择范围

cod*_*der 1 vb.net excel range selection

这是我的代码:

Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Excel files (*.xls)|*.xls"
saveFileDialog1.Title = "Save File"
saveFileDialog1.RestoreDirectory = True

If saveFileDialog1.ShowDialog() = DialogResult.OK Then
    Try
        Dim ExcelApp As New Microsoft.Office.Interop.Excel.Application()
        ExcelApp.Application.Workbooks.Add(Type.Missing)
        ExcelApp.Cells.HorizontalAlignment = XlHAlign.xlHAlignLeft

        ' Change properties of the Workbook 
        ExcelApp.Columns.ColumnWidth = 15

        ' Storing header part in Excel
        For i As Integer = 1 To DataGridView1.Columns.Count
            ExcelApp.Cells(1, i) = DataGridView1.Columns(i - 1).HeaderText
        Next

        ' Storing Each row and column value to excel sheet
        For i As Integer = 0 To DataGridView1.Rows.Count - 2
            For j As Integer = 0 To DataGridView1.Columns.Count - 1
                ExcelApp.Cells(i + 2, j + 1) = DataGridView1.Rows(i).Cells(j).Value.ToString()
            Next
        Next

        Dim Destinationpath As String = saveFileDialog1.FileName
        ExcelApp.ActiveWorkbook.SaveAs(Destinationpath)
        ExcelApp.ActiveWorkbook.Saved = True
        ExcelApp.Quit()
        MsgBox("Record exported successfully", MsgBoxStyle.Information)
    Catch
        MsgBox("It is being used by another process.Please close it and retry.", MsgBoxStyle.Critical)
    End Try
Else
End If
Run Code Online (Sandbox Code Playgroud)

现在,如何使用上面填充在 Excel 工作表中的代码来选择范围。

cod*_*der 5

找到了答案:

Dim lastrow As Range = ExcelApp.Rows.End(XlDirection.xlDown)
Dim findme As Range = ExcelApp.Range("A1:E" & lastrow.Row)
MsgBox("A1:E" & lastrow.Row)
Run Code Online (Sandbox Code Playgroud)