VBA/Excel/Access/Word/Language Basics/Const

Материал из VB Эксперт
Перейти к: навигация, поиск

Constants can be declared on one line if separated by commas

   <source lang="vb">

Const Age As Integer = 25, City As String = "Denver", PayCheck As Currency = 350 Sub severalConst()

  MsgBox Age
  MsgBox City
  MsgBox PayCheck

End Sub

</source>
   
  


Make a constant available to all modules in your application, use the Public keyword in front of the Const statement.

   <source lang="vb">

Public Const NumOfChar = 255 Sub publicConst()

  MsgBox NumOfChar

End Sub

</source>
   
  


To make a constant available within a single procedure, you declare it at the procedure level

   <source lang="vb">

Sub ageSub()

   Const Age As Integer = 25
   "...instructions...

End Sub

</source>
   
  


Use a constant in all the procedures of a module, use the Private keyword in front of the Const statement

   <source lang="vb">

Private Const dsk = "B:" Sub privateConst()

 MsgBox dsk

End Sub

</source>
   
  


use a Constant to store the PI

   <source lang="vb">

Sub constDemo()

    Const Pi = 3.14159265358979

End Sub

</source>
   
  


When declaring a constant, you can use any one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String, or Variant

   <source lang="vb">

Sub constDec()

   Const dialogName = "Enter Data"
   Const slsTax = 8.5
   Const Discount = 0.5
   Const ColorIdx = 3
   MsgBox slsTax

End Sub

</source>
   
  


Working with Date type value Constants

   <source lang="vb">

Sub constDemo()

   Const conVenue As String = "Hall"
   Const conDate As Date = #12/31/2005#
   MsgBox "The concert is at " & conVenue & " on " & conDate & "."

End Sub

</source>
   
  


Working with pre-defined Constant

   <source lang="vb">

Sub CalcManual()

   Application.Calculation = xlCalculationManual
   MsgBox xlCalculationAutomatic

End Sub

</source>
   
  


Working with Symbolic Constants

   <source lang="vb">

Private Const TAXRATE As Currency = 0.0875 Function TotalAmount(curSaleAmount As Currency)

  TotalAmount = curSaleAmount * TAXRATE

End Function

</source>