在活动工作表上插入数据

时间:2016-08-25 12:01:33

标签: vb.net excel

我试图在excel的活动表格中插入数据

    Sub click()
    Dim oExcel As Object
    Dim oBook As Object
    Dim oSheet As Object

    'Start a new workbook in Excel
    oExcel = CreateObject("Excel.Application")
    oBook = oExcel.Workbooks.Add


    'Add data to cells of the first worksheet in the new workbook
    oSheet = oBook.Worksheets(1)
    oSheet.Range("A1").Value = "Last Name"
    oSheet.Range("B1").Value = "First Name"
    oSheet.Range("A1:B1").Font.Bold = True
    oSheet.Range("A2").Value = "Doe"
    oSheet.Range("B2").Value = "John"

    'Save the Workbook and Quit Excel
    oBook.SaveAs("c:\abc.xlsx")
    oExcel.Quit
End Sub

这段代码的作用是单击按钮(按钮出现在excel的功能区中),上面的函数被调用。创建新工作表并将数据输入其中。 实际上我想要的是在不创建文件的情况下将数据插入当前工作表。

请任何可以提供帮助的人

提前致谢

2 个答案:

答案 0 :(得分:0)

如果代码在Excel中,那么这将起作用:

Sub click()
    With ActiveSheet
        .Range("A1").Value = "Last Name"
        .Range("B1").Value = "First Name"
        .Range("A1:B1").Font.Bold = True
        .Range("A2").Value = "Doe"
        .Range("B2").Value = "John"
    End With
End Sub

从其他应用程序(如Access)可以使用:

Sub click1()
    Dim oExcel As Object
    Dim oBook As Workbook
    Dim oSheet As Object

    'Start a new workbook in Excel
    Set oExcel = CreateObject("Excel.Application")
    Set oBook = oExcel.Workbooks.Open("c:\def.xlsx")

    'Add data to cells of the first worksheet in the opened workbook
    Set oSheet = oBook.Worksheets(1)
    With oSheet
        .Range("A1").Value = "Last Name"
        .Range("B1").Value = "First Name"
        .Range("A1:B1").Font.Bold = True
        .Range("A2").Value = "Doe"
        .Range("B2").Value = "John"
    End With

    'Save the Workbook and Quit Excel
    oBook.SaveAs ("c:\abc.xlsx")
    oExcel.Quit
End Sub

注意:如果您想以同一名称保存,请使用oBook.Save
       如果您希望Excel在显示后显示,请使用oExcel.Visible = True

答案 1 :(得分:0)

这很简单......这就是我们如何获取当前工作簿的访问权限而无需创建或保存文件

 Dim activeWorksheet As Excel.Worksheet = CType(Globals.ThisAddIn.Application.ActiveSheet, Excel.Worksheet)
    With activeWorksheet
        .Range("A1").Value = "Last Name"
        .Range("B1").Value = "First Name"
        .Range("A1:B1").Font.Bold = True
        .Range("A2").Value = "Doe"
        .Range("B2").Value = "John"
    End With