Write value to specific cell to Workbook with VBA code using VB.NET
I have code in Excel VBA that finds a specific value in column 2 and writes the value in that found rows column 3:
ThisWorkbook.Worksheets("Sheet1").Cells(Cells.Find("ProjectNumber", lookat:=xlWhole).Row, 3).Value = "TEST"
I am trying to get that function to run from my Visual Studio application.
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
It is giving me errors like
xlwhole is not declared
and
cells is not declared
My understanding is it should be coming from the type library of Excel and code such as:
xlWorkSheet.Cells(2, 5) = "TEST"
which does use "cells".
You need to fully qualify each enumeration. In this case,
Excel.XlLookAt.xlWhole
XlLookAt enumeration (Excel)
In an Excel/VBA environment, they are just a basic enumeration.
Cells
in your code is also not fully qualified. Cells.Find
needs a worksheet qualifier. VB.NET does not know what Cells
is without a qualifier. Again, in a VBA environment, you do not have to be this explicit, but in VB.NET you do, as there is no "default context"
Your xlWorkSheet
variable is not indexed. It's already holding a single reference to xlWorkBook.Worksheets("Sheet1")
- So you don't specify the name of it again.
Also, you should store the result of the Find
in a Range
variable before using it instead of trying to do it all in one line. Then you can check to see if it "didn't find anything" before you try to use the result, and can even see what the result is before taking action
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