Introduction
In VBA, Interior.Color
is used to change the background color of a cell in Excel. However, in VB.NET, the method is different due to its distinct libraries. In this article from Radib explains how to achieve the same functionality in VB.NET.
Buy a virtual server at an economical price from Radib, click here
1. VBA Code Using Interior.Color
Sub ChangeColorVBA()
Range("A1").Interior.Color = RGB(255, 0, 0) ' Change background color to red
End Sub
2. Equivalent Code in VB.NET
Imports Microsoft.Office.Interop.Excel
Module Module1
Sub Main()
Dim xlApp As New Application()
Dim xlWorkbook As Workbook = xlApp.Workbooks.Open("C:\example.xlsx")
Dim xlWorksheet As Worksheet = xlWorkbook.Sheets(1)
xlWorksheet.Range("A1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
xlWorkbook.Save()
xlWorkbook.Close()
xlApp.Quit()
End Sub
End Module
3. Explanation of VB.NET Code
- Create an Excel application object:
Dim xlApp As New Application()
- Open an Excel file:
Dim xlWorkbook As Workbook = xlApp.Workbooks.Open("C:\example.xlsx")
- Select a worksheet:
Dim xlWorksheet As Worksheet = xlWorkbook.Sheets(1)
- Change the cell’s background color:
xlWorksheet.Range("A1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
- Save and close the file.
4. Conclusion
While VBA uses Interior.Color = RGB(255, 0, 0)
, VB.NET requires System.Drawing.ColorTranslator.ToOle()
. Also, in VB.NET, we must handle the Excel objects explicitly.