当前位置: 代码迷 >> VB Dotnet >> vb读写 Excel操作参考解决办法
  详细解决方案

vb读写 Excel操作参考解决办法

热度:1128   发布时间:2016-04-25 02:25:41.0
vb读写 Excel操作参考
个人备考


Imports Microsoft.Office.Interop


Public Class Form1
    Dim newxls As Excel.Application
    Dim newbook As Excel.Workbook
    Dim newsheet As Excel.Worksheet
    Dim newrange As Excel.Range

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim filesbrow As FolderBrowserDialog = New FolderBrowserDialog
        Dim filename As String = String.Empty
        If filesbrow.ShowDialog = Windows.Forms.DialogResult.OK Then
            filename = filesbrow.SelectedPath & "\abc.xls"
        Else
            Exit Sub
        End If

        Dim systime As String = Now.Date.ToString("yyyyMMdd")
        newxls = CreateObject("Excel.application")
        If IO.File.Exists(filename) Then
            newbook = newxls.Workbooks.Open(filename)
        Else
            newbook = newxls.Workbooks.Add()
        End If

        Dim hasFlg As String = "0"
        Dim count As Integer = newbook.Worksheets.Count
        For i As Integer = 1 To newbook.Worksheets.Count
            newsheet = newbook.Worksheets(i)
            If newsheet.Name = systime Then
                hasFlg = "1"
                Exit For
            End If
        Next
        If hasFlg = "0" Then
            Try
                newsheet = newbook.Worksheets.Add(After:=newbook.Worksheets(count))
                newsheet.Name = systime
            Catch ex As Exception
                newxls.Workbooks.Close()
                newxls.Quit()
                Exit Sub
            End Try
        End If
        newxls.ActiveWorkbook.SaveAs(filename, True)
        newxls.Workbooks.Close()
        newxls.Quit()

    End Sub
End Class

------解决方案--------------------
  相关解决方案