将值写入Excel单元格

时间:2017-04-27 14:38:11

标签: excel vb.net excel-interop

我的目标是创建一个带有按钮的简单功能区,该按钮将单元格(A1)值设置为“Hello World!”在活动工作表中。

我有这段代码,但它返回一个错误,我不知道我做错了什么。

错误的屏幕截图:

enter image description here

代码:

Imports Microsoft.Office.Tools.Ribbon
Imports Microsoft.Office.Interop.Excel

Public Class Ribbon1

    Private Sub Ribbon1_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As RibbonControlEventArgs) Handles Button1.Click
        Dim xlApp As New Excel.Application
        Dim xlBook As Excel.Workbook
        Dim xlSheet As Excel.Worksheet

        xlBook = xlApp.ActiveWorkbook
        xlSheet = xlBook.ActiveSheet

        With xlSheet
            .Range("A1").Value = "Hello World!"
        End With
    End Sub

End Class

1 个答案:

答案 0 :(得分:2)

您需要添加新的Workbook,然后才能对其执行任何操作:

xlApp.Workbooks.Add()

我还会考虑声明使用Range

Dim xlRange As Excel.Range = xlSheet.Range("A1")
xlRange.Value = "Hello World!"

您的代码看起来与此类似:

Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook = xlApp.Workbooks.Add()
Dim xlSheet As Excel.Worksheet = CType(xlBook.ActiveSheet, Excel.Worksheet)

Dim xlRange As Excel.Range = xlSheet.Range("A1")
xlRange.Value = "Hello World!"

另请转Option Strict On

  

将隐式数据类型转换限制为仅扩展转换,禁止后期绑定,并禁止导致Object类型的隐式类型。