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
Vba

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
VB.Net

3. Explanation of VB.NET Code

  • Create an Excel application object:
    Dim xlApp As New Application()
    
    VB.Net
  • Open an Excel file:
    Dim xlWorkbook As Workbook = xlApp.Workbooks.Open("C:\example.xlsx")
    
    VB.Net
  • Select a worksheet:
    Dim xlWorksheet As Worksheet = xlWorkbook.Sheets(1)
    
    VB.Net
  • Change the cell’s background color:
    xlWorksheet.Range("A1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)
    
    VB.Net
  • 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.

Was this answer helpful? 45 Users Found This Useful (45 Votes)