I have created a workbook template that will be used to collect some data from users.
I want to restrict user input to numbers between 0 and 20 in each worksheet range A1:C5 (say).
I know I can use a Macro like below to do it

    With oSheet
        Dim r As Integer = ds.Tables("tblStudents").Rows.Count + 1
        Dim UsedRange As Excel.Range = .range("F2:K" & r)

        For Each cell In UsedRange
            If cell.Value < 0 or cell.Value > 20 Then
                MsgBox(" Out of range")
                cell.Value = ""
            End If

    End With

How can I include this macro to each worksheet when creating the workbook in my VB code.

Create, Execute and delete Macro in excel using C#

There is also a VB .NET version in the post.

To add Microsoft.Vbe.Interop reference:

  • Project
  • Add Reference
  • .NET
  • Microsoft.Vbe.Interop

To add Microsoft.Office.Interop.Excel reference:
* Project
* Add Reference
* .NET
* Microsoft.Office.Interop.Excel

You must explicitly enable access to the Microsoft Office Visual Basic for Applications project system before you can create or open a Visual Studio Tools for the Microsoft Office System project