learner learner - 1 year ago 73
Vb.net Question

Insert data on active worksheet

I'm trying to insert the data in active sheet of 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
End Sub

What this code does is on click of the button (the button appears in ribbon of excel),the above function gets called.new sheet gets created and data gets entered into it.
Actually what I want is to insert data into current sheet without creating a file.

Please anyone who can helpout

Thanks in advance

Answer Source

It was pretty simple...this is how we can get the access to current sheet of workbook..without creating or saving a file

 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download