简体   繁体   中英

Why set value cell of excel not working in vb.net?

I create a sample add ins for excel by vb.net:

Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim excelApp As Excel.Application
            excelApp = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
            ' Dim xlwb As Excel.Workbook = Globals.ThisAddIn.Application.Worksheets.Add()
            ' dim sheet As Excel.Worksheet = xlwb.ActiveSheet
            Dim sheet As Excel.Worksheet
            sheet = excelApp.ActiveSheet
            sheet.Range("A1").Value = "OK"

            Me.Close()

        End Sub
    End Class

I set value for cell of excel : sheet.Range("A1").Value = "OK" but it doesn't set. Why? How fix?

Rather than declaring a Worksheet as a variable just call the worksheet directly based on its name. For example,

Sheets("Sheet1").Range("A1").Value = "OK"

This way you wont have multiple variable of worksheets.

I should also add that this would mean you have to have the correct workbook active.

Hope this helps

Greg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM