从按钮上的文本框刷新Excel工作表单击Visual Basic

时间:2017-02-12 17:06:18

标签: vb.net

我想创建一个代码,它会将文本框值发送到excel工作表。每次按下按钮时,文本框值都会替换前一个。我已经完成的工作就是将此值发送到excel工作表,但在每次新的点击中都会有一个新的工作簿开头。我应该改变什么?

这是代码

 Imports System.Data.OleDb
  Imports Excel = Microsoft.Office.Interop.Excel

 Public Class Form1
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Create a new instance of Excel and start a new workbook.
    objApp = New Excel.Application()
    objBooks = objApp.Workbooks
    objBook = objBooks.Add
    objSheets = objBook.Worksheets
    objSheet = objSheets(1)

    objSheet.Range("A1").Value = TextBox1.Text

    'Return control of Excel to the user.
    objApp.Visible = True
    objApp.UserControl = True

    'Clean up a little.
    objSheet = Nothing
    objSheets = Nothing
    objBooks = Nothing
End Sub
End Class

3 个答案:

答案 0 :(得分:1)

改变这个:

public boolean addGame(String team1, String team2) {
    boolean result;

    if (team1.equals(team2))
        result = false;

    }
    if (a game between two parameter teams has previously been added by
        earlier call to addGame){ 
        result = false;
    }
    else { 
        result = true; 
    }

objApp = New Excel.Application()

答案 1 :(得分:0)

我简化如下:

Public Class Form1
    Dim objApp As Excel.Application
    Dim objCell As Excel.Range    

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click    

        If objCell Is Nothing Then
            objApp = New Excel.Application()
            objCell = objApp.Workbooks.Add.Worksheets(1).Range("A1")
        End If   

        objCell.Value = TextBox1.Text

        'Return control of Excel to the user.
        objApp.Visible = True
        objApp.UserControl = True    

    End Sub
End Class

此代码应该更加健壮,以处理用户关闭Excel

等情况

答案 2 :(得分:0)

这终于完成了这项工作

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If objApp Is Nothing Then
        objApp = New Excel.Application()
    End If
    If objBooks Is Nothing Then
        objBooks = objApp.Workbooks
    End If
    If objBook Is Nothing Then
        objBook = objBooks.Add
    End If
    If objSheets Is Nothing Then
        objSheets = objBook.Worksheets
    End If
    If objSheet Is Nothing Then
        objSheet = objSheets(1)
    End If


    objSheet.Range("A1").Value = TextBox1.Text

    'Return control of Excel to the user.
    objApp.Visible = True
    objApp.UserControl = True

    'Clean up a little.
    objSheet = Nothing
    objSheets = Nothing
    objBooks = Nothing
End Sub 

谢谢大家的回复