excel - 使用 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"
它确实使用“细胞”。
解决方案
您需要完全限定每个枚举。在这种情况下,
Excel.XlLookAt.xlWhole
在 Excel/VBA 环境中,它们只是一个基本的枚举。
Cells
在您的代码中也不是完全合格的。Cells.Find
需要一个工作表限定符。VB.NET 不知道什么Cells
是没有限定符的。同样,在 VBA 环境中,您不必如此明确,但在 VB.NET 中,您可以这样做,因为没有“默认上下文”
您的xlWorkSheet
变量未编入索引。它已经拥有一个对xlWorkBook.Worksheets("Sheet1")
- 的引用,因此您无需再次指定它的名称。
此外,您应该在使用它之前将结果存储Find
在Range
变量中,而不是尝试在一行中完成所有操作。然后您可以在尝试使用结果之前检查它是否“没有找到任何东西”,甚至可以在采取行动之前查看结果是什么
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
推荐阅读
- vue.js - 使用 vue 中的嵌套组件将数据返回到根目录
- python - 如何将可能包含数字的字符串中的第一个字母大写
- xamarin - 将按钮悬停在 Xamarin 表单 UWP 时删除边框
- alloy - 没有反例的断言就代表结论?
- c# - 优雅地解析 JSON
- javascript - 更改事件未触发
- javascript - document.write 在 IE 和 Edge 下不起作用
- r - 将图像添加到 R 中的 ppt 模板
- html - 为什么 flex-wrap: wrap 在 safari 上不起作用
- ruby - 如何检查 PDF 文件是否与 Ruby/Rspec 有链接?