首页 > 解决方案 > 使用 VB.NET 使用 VBA 代码将特定单元格的值写入工作簿

问题描述

我在 Excel VBA 中有代码,它在第 2 列中找到一个特定值并将该值写入找到的行第 3 列:

ThisWorkbook.Worksheets("Sheet1").Cells(Cells.Find("ProjectNumber", lookat:=xlWhole).Row, 3).Value = "TEST"

我正在尝试从我的 Visual Studio 应用程序中运行该功能。

Imports Excel = Microsoft.Office.Interop.Excel
Module Automate_Excel

Public xlApp As Excel.Application = Nothing
Public xlWorkBook As Excel.Workbook = Nothing
Public xlWorkSheet As Excel.Worksheet = Nothing
Sub Excel_FinishProject()

    xlApp = New Excel.Application
    xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
    xlApp.Visible = True
    xlWorkSheet = xlWorkBook.Worksheets("sheet1")

'Write
    xlWorksheet("Sheet1").Cells(Cells.Find("ProjectNumber", lookat:=xlWhole).Row, 3).Value = "TEST"

    xlWorkBook.Close()
    xlApp.Quit()
End Sub

End Module

它给了我这样的错误

xlwhole 未声明

未声明单元格

我的理解是它应该来自Excel的类型库和代码,例如:

xlWorkSheet.Cells(2, 5) = "TEST"

它确实使用“细胞”。

标签: excelvbavb.net

解决方案


您需要完全限定每个枚举。在这种情况下,

Excel.XlLookAt.xlWhole 

XlLookAt 枚举 (Excel)

在 Excel/VBA 环境中,它们只是一个基本的枚举。

Cells在您的代码中也不是完全合格的。Cells.Find需要一个工作表限定符。VB.NET 不知道什么Cells是没有限定符的。同样,在 VBA 环境中,您不必如此明确,但在 VB.NET 中,您可以这样做,因为没有“默认上下文”

您的xlWorkSheet变量未编入索引。它已经拥有一个对xlWorkBook.Worksheets("Sheet1")- 的引用,因此您无需再次指定它的名称。

此外,您应该在使用它之前将结果存储FindRange变量中,而不是尝试在一行中完成所有操作。然后您可以在尝试使用结果之前检查它是否“没有找到任何东西”,甚至可以在采取行动之前查看结果是什么

xlWorkSheet = xlWorkBook.Worksheets("Sheet1")
Dim result as Excel.Range = xlWorkSheet.Cells.Find("ProjectNumber", lookat:=Excel.XlLookAt.xlWhole)
If result IsNot Nothing Then
    ' xlWorkSheet.Cells(result.Row, 3).Value = "TEST"

    ' OP says this works instead
    xlWorkSheet.Cells(result.Row, 3) = "TEST"

End IF

推荐阅读