Vbscript-quick-guide

提供:Dev Guides
移動先:案内検索

VBScript-概要

  • VB * Scriptは、* V isual B * asic Sc​​riptingの略で、Visual Basic for Applications(VBA)のサブセットを形成します。 VBAはMicrosoftの製品であり、MS ProjectやMS Officeなどの他のMicrosoft製品だけでなく、AUTO CADなどのサードパーティツールにも含まれています。

VBScriptの機能

  • VBScriptは、非常に高速なインタープリターを備えた軽量のスクリプト言語です。
  • ほとんどの場合、VBScriptは大文字と小文字を区別しません。 非常にシンプルな構文で、習得と実装が簡単です。
  • C ++やJavaとは異なり、VBScriptはオブジェクトベースのスクリプト言語であり、オブジェクト指向プログラミング言語ではありません。
  • 実行中の環境の要素にアクセスするために、コンポーネントオブジェクトモデル*(COM)を使用します。 *VBScriptが正常に実行されるのは、Internet Explorer (IE)、Internet Information Services *(IIS)、Windows Scripting Host *(WSH)*などのホスト環境で実行された場合のみです。

VBscript –バージョン履歴と使用

VBScriptは1996年にMicrosoftによって導入され、その最初のバージョンは1.0でした。 VBScriptの現在の安定バージョンは5.8で、IE8またはWindows 7の一部として利用可能です。 VBScriptの使用領域は豊富で、以下のリストに制限されていません。

  • VBScriptは、人気のある自動化テストツールの1つ( QTP と略されるQuick Test Professional)のスクリプト言語として使用されます。
  • Windows Scripting Host。主にWindowsデスクトップを自動化するためにWindowsシステム管理者が使用します。 Active Server Pages (ASP)*、VBScriptまたはJava Scriptを使用する動的なWebページを作成するためのサーバー側スクリプト環境。
  • VBScriptは、Microsoft Internet Explorerのクライアント側スクリプトに使用されます。
  • Microsoft Outlookフォームは通常VBScriptで実行されます。ただし、アプリケーションレベルのプログラミングはVBAに依存しています(Outlook 2000以降)。

デメリット

  • VBscriptはIEブラウザでのみ使用されます。 Chrome、Firefoxなどの他のブラウザーはVBScriptをサポートしません。 したがって、JavaScriptはVBScriptよりも優先されます。
  • VBScriptのコマンドラインサポートは制限されています。
  • デフォルトでは利用可能な開発環境がないため、デバッグは困難です。

VBScriptは現在どこにありますか?

VBScriptの現在のバージョンは5.8であり、.NETフレームワークの最近の開発により、MicrosoftはWeb開発のためにASP.NET内でVBScriptの将来のサポートを提供することを決定しました。 したがって、VBScriptエンジンの新しいバージョンはこれ以上ありませんが、欠陥を修正するすべての問題とセキュリティの問題は、Microsoftのサポートエンジニアリングチームによって対処されています。 ただし、VBScriptエンジンは、デフォルトですべてのMicrosoft WindowsおよびIISの一部として出荷されます。

VBScript-構文

初めてのVBScript

「Hello World」を出力するVBScriptを作成しましょう。

<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         document.write("Hello World!")
      </script>
   </body>
</html>

上記の例では、HTMLドキュメントに文字列を書き込む_document.write_関数を呼び出しました。 この関数は、テキスト、HTML、またはその両方を記述するために使用できます。 したがって、上記のコードは次の結果を表示します-

Hello World!

空白と改行

VBScriptは、VBScriptプログラム内に表示されるスペース、タブ、および改行を無視します。 プログラム内でスペース、タブ、改行を自由に使用できるため、コードを読みやすく、理解しやすいきちんとした一貫した方法で自由にフォーマットおよびインデントできます。

フォーマット

VBScriptは、MicrosoftのVisual Basicに基づいています。 JavaScriptとは異なり、特定のステートメントを終了するためにセミコロンなどのステートメントターミネータは使用されません。

単一行の構文

コロンは、VBScriptの2行以上を1行で記述する必要がある場合に使用されます。 したがって、VBScriptでは、コロンは行区切り記号として機能します。

<script language = "vbscript" type = "text/vbscript">
   var1 = 10 : var2 = 20
</script>

複数行の構文

VBScriptのステートメントが長く、ユーザーがそれを複数の行に分割する場合、ユーザーはアンダースコア「_」を使用する必要があります。 これにより、コードの可読性が向上します。 次の例は、複数の行を扱う方法を示しています。

<script language = "vbscript" type = "text/vbscript">
   var1 = 10
   var2 = 20
   Sum = var1 + var2
   document.write("The Sum of two numbers"&_"var1 and var2 is " & Sum)
</script>

予約語

次のリストは、VBScriptの予約語を示しています。 これらの予約語は、定数、変数、またはその他の識別子名として使用しないでください。

Loop LSet Me
Mod New Next
Not Nothing Null
On Option Optional
Or ParamArray Preserve
Private Public RaiseEvent
ReDim Rem Resume
RSet Select Set
Shared Single Static
Stop Sub Then
To True Type
And As Boolean
ByRef Byte ByVal
Call Case Class
Const Currency Debug
Dim Do Double
Each Else ElseIf
Empty End EndIf
Enum Eqv Event
Exit False For
Function Get GoTo
If Imp Implements
In Integer Is
Let Like Long
TypeOf Until Variant
Wend While With
Xor Eval Execute
Msgbox Erase ExecuteGlobal
Option Explicit Randomize SendKeys

大文字と小文字の区別

VBScriptは、*大文字と小文字を区別しない言語*です。 これは、言語キーワード、変数、関数名、およびその他の識別子を、一貫した大文字で入力する必要がないことを意味します。 したがって、int_counter、INT_Counter、およびINT_COUNTERの識別子は、VBScript内で同じ意味を持ちます。

VBScriptのコメント

コメントは、プログラムロジックと、他のプログラマが将来同じコードでシームレスに作業できるユーザー情報を文書化するために使用されます。 開発者、変更者などの情報を含めることができ、組み込まれたロジックを含めることもできます。 コメントは実行中にインタプリタによって無視されます。 VBScriptのコメントは、2つの方法で示されます。

1. 単一引用符( ’)で始まるステートメントはコメントとして扱われます。

以下は例です-

<script language = "vbscript" type = "text/vbscript">
   <!—
      ' This Script is invoked after successful login
      ' Written by : finddevguides
      ' Return Value : True/False
  //- >
</script>

2. キーワード「REM」で始まるステートメント。

以下は例です-

<script language = "vbscript" type = "text/vbscript">
   <!—
      REM This Script is written to Validate the Entered Input
      REM Modified by  : Tutorials point/user2
  //- >
</script>

ブラウザでVBScriptを有効にする

すべての最新ブラウザーがVBScriptをサポートしているわけではありません。 VBScriptはMicrosoftのInternet Explorerでのみサポートされていますが、他のブラウザー(FirefoxおよびChrome)はJavaScriptのみをサポートしています。 したがって、開発者は通常、VBScriptよりもJavaScriptを好みます。

Internet Explorer(IE)はVBScriptをサポートしていますが、この機能を手動で有効または無効にする必要がある場合があります。 このチュートリアルでは、Internet ExplorerでVBScriptサポートを有効または無効にする手順を認識します。

Internet ExplorerのVBScript

Internet ExplorerでVBScriptをオンまたはオフにする簡単な手順を次に示します-

  • メニューから[ツール]→[インターネットオプション]を選択します
  • ダイアログボックスから[セキュリティ]タブを選択します
  • [レベルのカスタマイズ]ボタンをクリックします
  • スクリプトオプションが見つかるまで下にスクロールします
  • [アクティブスクリプト]の下の[ラジオボタンを有効にする]を選択します。
  • 最後に[OK]をクリックして出てきます

Internet ExplorerでVBScriptサポートを無効にするには、 Active scripting の下の_Disable_オプションボタンを選択する必要があります。

VBScript-配置

HTMLファイルでのVBScriptの配置

HTMLドキュメントのどこにでもVBScriptコードを含めることができる柔軟性があります。 しかし、HTMLファイルにVBScriptを含める最も好ましい方法は次のとおりです-

  • <head> …​ </head>セクションのスクリプト。
  • <body> …​ </body>セクションのスクリプト。
  • <body> …​ </body>および<head> …​ </head>セクションのスクリプト。
  • 外部ファイルにスクリプトを作成し、<head> …​ </head>セクションに含めます。

次のセクションでは、VBScriptをさまざまな方法で配置する方法を説明します-

<head> …​ </head>セクションのVBScript

ユーザーがどこかをクリックしたときなど、何らかのイベントでスクリプトを実行したい場合は、次のように頭にそのスクリプトを配置します-

<html>
   <head>
      <script type = "text/Vbscript">
         <!--
            Function sayHello()
               Msgbox("Hello World")
            End Function
        //-->
      </script>
   </head>

   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello"/>
   </body>
</html>

次の結果が生成されます-SayHelloという名前のボタン。 ボタンをクリックすると、メッセージボックスが「Hello World」というメッセージとともにユーザーに表示されます。

<body> …​ </body>セクションのVBScript

スクリプトがページのコンテンツを生成するように、ページの読み込み時にスクリプトを実行する必要がある場合、スクリプトはドキュメントの<body>部分に配置されます。 この場合、VBScriptを使用して定義された関数はありません-

<html>
   <head> </head>
   <body>
      <script type = "text/vbscript">
         <!--
            document.write("Hello World")
        //-->
      </script>
      <p>This is web page body </p>
   </body>
</html>

これは、次の結果を生成します-

Hello World
This is web page body

<body>および<head>セクションのVBScript

次のように、VBScriptコードを<head>セクションと<body>セクションにまとめて配置できます-

<html>
   <head>
      <script type = "text/vbscript">
         <!--
            Function sayHello()
               msgbox("Hello World")
            End Function
        //-->
      </script>
   </head>

   <body>
      <script type = "text/vbscript">
         <!--
         document.write("Hello World")
        //-->
      </script>
      <input type = "button" onclick = "sayHello()" value = "Say Hello"/>
   </body>
</html>

「Say Hello」ボタンが付いたHello Worldメッセージ-次の結果が生成されます。 ボタンをクリックすると、メッセージ「Hello World」を含むメッセージボックスがユーザーに表示されます。

Hello World

外部ファイルのVBScript

VBScriptでより広範囲に作業を開始すると、サイトの複数のページで同一のVBScriptコードを再利用している場合があります。 複数のHTMLファイルで同一のコードを維持することに制限されません。

_script_タグは、VBScriptを外部ファイルに保存し、それをHTMLファイルに含めることができるメカニズムを提供します。 _script_タグとその_src_属性を使用して、HTMLコードに外部VBScriptファイルを含める方法を示す例があります-

<html>
   <head>
      <script type = "text/vbscript" src = "filename.vbs" ></script>
   </head>
   <body>
      .......
   </body>
</html>

外部ファイルソースからVBScriptを使用するには、すべてのVBScriptソースコードを拡張子「.vbs」の単純なテキストファイルに記述し、上記のようにそのファイルを含める必要があります。 たとえば、filename.vbsファイルに次のコンテンツを保持し、filename.vbsファイルを含めた後、HTMLファイルで_sayHello_関数を使用できます。

Function sayHello()
   Msgbox "Hello World"
End Function

QTPでのVBScriptの配置

VBScriptはQTP(Quick Test Professional)ツールに配置されますが、HTMLタグで囲まれていません。 スクリプトファイルは拡張子.vbsで保存され、Quick Test Professional実行エンジンによって実行されます。

VBScript-変数

VBScript変数

変数は、スクリプトの実行中に変更できる値を保持するために使用される名前付きメモリの場所です。 VBScriptには Variant という基本データ型のみがあります。

変数を宣言するためのルール-

  • 変数名はアルファベットで始まる必要があります。
  • 変数名は255文字を超えることはできません。
  • 変数にはピリオド(。)を含めないでください
  • 変数名は、宣言されたコンテキスト内で一意である必要があります。

変数を宣言する

変数は「dim」キーワードを使用して宣言されます。 基本データ型は1つしかないため、宣言された変数はすべてデフォルトでバリアントです。 そのため、ユーザーは宣言中にデータの種類を*必要としない*必要があります。

  • 例1 *-この例では、IntValueを文字列、整数、または配列として使用できます。
Dim Var
  • 例2 *-2つ以上の宣言がコンマ(、)で区切られている
Dim Variable1,Variable2

変数への値の割り当て

値は代数式と同様に割り当てられます。 左側の変数名の後に等号(=)記号が続き、右側にその値が続きます。

規則

  • 数値は二重引用符なしで宣言する必要があります。
  • 文字列値は二重引用符( ")で囲む必要があります
  • 日付と時刻の変数はハッシュ記号(#)で囲む必要があります

' Below Example, The value 25 is assigned to the variable.
Value1 = 25

' A String Value ‘VBScript’ is assigned to the variable StrValue.
StrValue = “VBScript”

' The date 01/01/2020 is assigned to the variable DToday.
Date1 = #01/01/2020#

' A Specific Time Stamp is assigned to a variable in the below example.
Time1 = #12:30:44 PM#

変数の範囲

変数は、変数のスコープを決定する次のステートメントを使用して宣言できます。 変数のスコープは、プロシージャまたはクラス内で使用される場合に重要な役割を果たします。

  • Dim
  • パブリック
  • 非公開

Dim

プロシージャレベルで「Dim」キーワードを使用して宣言された変数は、同じプロシージャ内でのみ使用できます。 スクリプトレベルで「Dim」キーワードを使用して宣言された変数は、同じスクリプト内のすべてのプロシージャで使用できます。

-次の例では、Var1とVar2の値はスクリプトレベルで宣言され、Var3はプロシージャレベルで宣言されています。

注意-この章の範囲は変数を理解することです。 機能については、今後の章で詳しく説明します。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim Var1
         Dim Var2

         Call add()
         Function add()
            Var1 = 10
            Var2 = 15
            Dim Var3
            Var3 = Var1 + Var2
            Msgbox Var3 'Displays 25, the sum of two values.
         End Function

         Msgbox Var1   ' Displays 10 as Var1 is declared at Script level
         Msgbox Var2   ' Displays 15 as Var2 is declared at Script level
         Msgbox Var3   ' Var3 has No Scope outside the procedure. Prints Empty
      </script>
   </body>
</html>

パブリック

「パブリック」キーワードを使用して宣言された変数は、関連するすべてのスクリプトのすべての手順で使用できます。 タイプが「public」の変数を宣言すると、Dimキーワードは「Public」に置き換えられます。

-次の例では、Var1とVar2はスクリプトレベルで使用できますが、Var3はパブリックとして宣言されているため、関連するスクリプトとプロシージャ全体で使用できます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim Var1
         Dim Var2
         Public Var3

         Call add()

         Function add()
            Var1 = 10
            Var2 = 15
            Var3 = Var1+Var2
            Msgbox Var3 'Displays 25, the sum of two values.
         End Function

         Msgbox Var1   ' Displays 10 as Var1 is declared at Script level
         Msgbox Var2   ' Displays 15 as Var2 is declared at Script level
         Msgbox Var3   ' Displays 25 as Var3 is declared as Public

      </script>
   </body>
</html>

非公開

「プライベート」として宣言された変数は、宣言されたスクリプト内でのみスコープを持ちます。 タイプ「Private」の変数を宣言すると、Dimキーワードは「Private」に置き換えられます。

-次の例では、Var1とVar2がスクリプトレベルで使用できます。 Var3はプライベートとして宣言され、この特定のスクリプトでのみ使用可能です。 「プライベート」変数の使用は、クラス内でより顕著です。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim Var1
         Dim Var2
         Private Var3

         Call add()
         Function add()
            Var1 = 10
            Var2 = 15
            Var3 = Var1+Var2
            Msgbox Var3 'Displays the sum of two values.
         End Function

         Msgbox Var1   ' Displays 10 as Var1 is declared at Script level
         Msgbox Var2   ' Displays 15 as Var2 is declared at Script level
         Msgbox Var3   ' Displays 25 but Var3 is available only for this script.
      </script>
   </body>
</html>

VBScript-定数

定数は、スクリプトの実行中に変更できない値を保持するために使用される名前付きメモリの場所です。 ユーザーが定数値を変更しようとすると、スクリプトの実行はエラーで終了します。 定数は、変数の宣言と同じ方法で宣言されます。

定数の宣言

構文

[Public | Private] Const Constant_Name = Value

定数のタイプは、パブリックまたはプライベートです。 パブリックまたはプライベートの使用はオプションです。 パブリック定数はすべてのスクリプトとプロシージャで使用できますが、プライベート定数はプロシージャまたはクラス内で使用できます。 宣言された定数には、数値、文字列、日付などの任意の値を割り当てることができます。

例1

この例では、piの値は3.4であり、メッセージボックスに円の領域が表示されます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim intRadius
         intRadius = 20
         const pi = 3.14
         Area = pi*intRadius*intRadius
         Msgbox Area

      </script>
   </body>
</html>

例2

以下の例は、文字列と日付値を定数に割り当てる方法を示しています。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Const myString = "VBScript"
         Const myDate = #01/01/2050#
         Msgbox myString
         Msgbox myDate

      </script>
   </body>
</html>

実施例3

以下の例では、ユーザーは定数値を変更しようとします。したがって、最終的に* Execution Error。*になります。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim intRadius
         intRadius = 20
         const pi = 3.14
         pi = pi*pi 'pi VALUE CANNOT BE CHANGED.THROWS ERROR'
         Area = pi*intRadius*intRadius
         Msgbox Area

      </script>
   </body>
</html>

VBScript-演算子

演算子とは何ですか?

式_4 + 5は9_に等しいとします。 ここでは、4と5は*オペランド*と呼ばれ、+は*演算子*と呼ばれます。 VBScript言語は、次の種類の演算子をサポートしています-

  • 算術演算子
  • 比較演算子
  • 論理(またはリレーショナル)演算子
  • 連結演算子

算術演算子

VBScriptは次の算術演算子をサポートしています-

変数Aが5を保持し、変数Bが10を保持すると仮定します-

リンク:/vbscript/vbscript_arithmetic_operators [例を表示]

Operator Description Example
+ Adds two operands A + B will give 15
- Subtracts second operand from the first A - B will give -5
* Multiply both operands A* B will give 50
/ Divide numerator by denumerator B/A will give 2
% Modulus Operator and remainder of after an integer division B MOD A will give 0
^ Exponentiation Operator B ^ A will give 100000

これらの演算子をよりよく理解するには、http://www.compileonline.com/execute_vbscript_online.php [自分で試してみてください]を使用できます。

比較演算子

VBScript言語でサポートされている次の比較演算子があります-

変数Aが10を保持し、変数Bが20を保持すると仮定します-

リンク:/vbscript/vbscript_comparison_operators [例を表示]

Operator Description Example
= Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is False.
<> Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A <> B) is True.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is False.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is True.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is False.
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A ⇐ B) is True.

これらの演算子をよりよく理解するには、http://www.compileonline.com/execute_vbscript_online.php [自分で試してみてください]を使用できます。

論理演算子

VBScript言語でサポートされている次の論理演算子があります-

変数Aが10を保持し、変数Bが0を保持すると仮定します-

リンク:/vbscript/vbscript_logical_operators [例を表示]

Operator Description Example
AND Called Logical AND operator. If both the conditions are True, then Expression becomes True. a<>0 AND b<>0 is False.
OR Called Logical OR Operator. If any of the two conditions is True, then condition becomes True. a<>0 OR b<>0 is true.
NOT Called Logical NOT Operator. It reverses the logical state of its operand. If a condition is True, then the Logical NOT operator will make it False. NOT(a<>0 OR b<>0) is false.
XOR Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to True, result is True. (a<>0 XOR b<>0) is true.

これらの演算子をよりよく理解するには、http://www.compileonline.com/execute_vbscript_online.php [自分で試してみてください]を使用できます。

連結演算子

VBScript言語でサポートされている次の連結演算子があります-

変数Aが5を保持し、変数Bが10を保持すると仮定します-

リンク:/vbscript/vbscript_concatenation_operators [例を表示]

Operator Description Example
+ Adds two Values as Variable Values are Numeric A + B will give 15
& Concatenates two Values A & B will give 510

変数A = "Microsoft"と変数B = "VBScript"を仮定し、その後-

Operator Description Example
+ Concatenates two Values A + B will give MicrosoftVBScript
& Concatenates two Values A & B will give MicrosoftVBScript

注意-数字と文字列には連結演算子を使用できます。 変数が数値または文字列値を保持する場合、出力はコンテキストに依存します。

これらの演算子をより良い方法で理解するには、http://www.compileonline.com/execute_vbscript_online.php [自分で試してみてください]を使用できます。

VBScript-意思決定

意思決定により、プログラマはスクリプトまたはそのセクションの実行フローを制御できます。 実行は、1つ以上の条件ステートメントによって管理されます。

以下は、ほとんどのプログラミング言語で見られる典型的な意思決定構造の一般的な形式です-

VBScriptの意思決定ステートメント

VBScriptは、次の種類の意思決定ステートメントを提供します。

Statement Description
if statement An *if *statement consists of a Boolean expression followed by one or more statements.
if..else statement An* if else statement consists of a Boolean expression followed by one or more statements. If the condition is True, the statements under the If statements are executed. If the condition is false, then the Else *part of the script is Executed
if…​elseif..else statement An* if statement followed by one or more ElseIf *Statements, that consists of Boolean expressions and then followed by an optional else statement, which executes when all the condition becomes false.
nested if statements An* if or elseif statement inside another if or elseif *statement(s).
switch statement A* switch* statement allows a variable to be tested for equality against a list of values.

VBScript-ループ

コードのブロックを数回実行する必要がある場合があります。 一般に、ステートメントは順番に実行されます。関数の最初のステートメントが最初に実行され、次に2番目のステートメントが実行されます。

プログラミング言語は、より複雑な実行パスを可能にするさまざまな制御構造を提供します。 ループステートメントを使用すると、ステートメントまたはステートメントのグループを複数回実行できます。VBScriptのループステートメントの一般的なものは次のとおりです。

ループアーキテクチャ

VBScriptは、ループ要件を処理するために次の種類のループを提供します。 詳細を確認するには、次のリンクをクリックしてください。

Loop Type Description
for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
for ..each loop It is executed if there is at least one element in group and reiterated for each element in a group.
while..wend loop It tests the condition before executing the loop body.
do..while loops The do..While statements will be executed as long as condition is True.(i.e.,) The Loop should be repeated till the condition is False.
do..until loops The do..Until statements will be executed as long as condition is False.(i.e.,) The Loop should be repeated till the condition is True.

ループ制御ステートメント

ループ制御ステートメントは、通常のシーケンスから実行を変更します。 実行がスコープを離れると、ループ内の残りのステートメントはすべて実行されません。

VBScriptは、次の制御ステートメントをサポートしています。 詳細を確認するには、次のリンクをクリックしてください。

Control Statement Description
Exit For statement Terminates the *For loop *statement and transfers execution to the statement immediately following the loop
Exit Do statement Terminates the* Do While* statement and transfers execution to the statement immediately following the loop

VBScript-イベント

イベントとは?

VBScriptのHTMLとの対話は、ユーザーまたはブラウザーがページを操作するときに発生するイベントを通じて処理されます。 ページが読み込まれると、それがイベントになります。 ユーザーがボタンをクリックすると、そのクリックもイベントになります。 イベントの他の例には、キーを押す、ウィンドウを閉じる、ウィンドウのサイズを変更するなどがあります。 開発者はこれらのイベントを使用して、VBScriptでコード化された応答を実行できます。これにより、ボタンがウィンドウを閉じ、メッセージがユーザーに表示され、データが検証されます。

イベントはドキュメントオブジェクトモデル(DOM)の一部であり、すべてのHTML要素には特定のイベントセットがあり、VBScriptコードをトリガーできます。 link:/vbscript/vbscript_events_html_ref [HTMLイベントリファレンス]の理解を深めるには、この小さなチュートリアルをご覧ください。 ここでは、EventとVBScriptの関係を理解するためのいくつかの例を見ていきます。

onclickイベントタイプ

これは最も頻繁に使用されるイベントタイプで、ユーザーがマウスの左ボタンをクリックしたときに発生します。 このイベントタイプに対して検証、警告などを設定できます。

<html>
   <head>
      <script language = "vbscript" type = "text/vbscript">
         Function sayHello()
            msgbox "Hello World"
         End Function
      </script>
   </head>

   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello"/>
   </body>
</html>

次の結果が生成されます。Helloボタンをクリックすると、onclickイベントが発生し、sayHello()関数がトリガーされます。

onsubmitイベントタイプ

もう1つの最も重要なイベントタイプは、_onsubmit_です。 このイベントは、フォームを送信しようとしたときに発生します。 したがって、このイベントタイプに対してフォーム検証を行うことができます。 [送信]ボタンをクリックしてフォームを送信すると、メッセージボックスが表示されます。

[送信]ボタンをクリックしてフォームを送信すると、メッセージボックスが表示されます。

<html>
   <head> </head>
   <body>
      <script language = "VBScript">
         Function fnSubmit()
            Msgbox("Hello finddevguides.Com")
         End Function
      </script>

      <form action = "/cgi-bin/test.cgi" method = "post" name = "form1" onSubmit = "fnSubmit()">
         <input name = "txt1" type = "text"><br>
         <input name = "btnButton1" type = "submit" value="Submit">
      </form>
   </body>
</html>

onmouseoverとonmouseout

これらの2つのイベントタイプは、画像やテキストでも素敵な効果を作成するのに役立ちます。 _onmouseover_イベントは、要素の上にマウスを置くと発生し、_onmouseout_はその要素からマウスを取り出すと発生します。

<html>
   <head> </head>
   <body>
      <script language = "VBScript">
         Function AlertMsg
            Msgbox("ALERT !")
         End Function

         Function onmourse_over()
            Msgbox("Onmouse Over")
         End Function

         Sub txt2_OnMouseOut()
            Msgbox("Onmouse Out !!!")
         End Sub

         Sub btnButton_OnMouseOut()
            Msgbox("onmouse out on Button !")
         End Sub
      </script>

      <form action = "page.cgi" method = "post" name = "form1">
         <input name = "txt1" type = "text" OnMouseOut = "AlertMsg()"><br>
         <input name = "txt2" type = "text" OnMouseOver = "onmourse_over()">
         <br><input name = "btnButton" type = "button" value = "Submit">
      </form>
   </body>
</html>

マウスをテキストボックスの上に置いたとき、およびフォーカスをテキストボックスとボタンから遠ざけたときに結果を生成します。

HTML 4標準イベント

参照用に、標準のHTML 4イベントをここにリストします。 ここで、スクリプトはそのイベントに対して実行されるVBScript関数を示します。

Event Value Description
onchange script Script runs when the element changes
onsubmit script Script runs when the form is submitted
onreset script Script runs when the form is reset
onblur script Script runs when the element loses focus
onfocus script Script runs when the element gets focus
onkeydown script Script runs when key is pressed
onkeypress script Script runs when key is pressed and released
onkeyup script Script runs when key is released
onclick script Script runs when a mouse click
ondblclick script Script runs when a mouse double-click
onmousedown script Script runs when mouse button is pressed
onmousemove script Script runs when mouse pointer moves
onmouseout script Script runs when mouse pointer moves out of an element
onmouseover script Script runs when mouse pointer moves over an element
onmouseup script Script runs when mouse button is released

VBScriptとCookie

クッキーとは?

WebブラウザとサーバーはHTTPプロトコルを使用して通信し、HTTPはステートレスプロトコルです。 ただし、商用Webサイトの場合、異なるページ間でセッション情報を維持する必要があります。 たとえば、多くのページを完了すると、1人のユーザー登録が終了します。 しかし、すべてのWebページにわたってユーザーのセッション情報を維持する方法。 多くの場合、Cookieを使用することは、ユーザーの利便性やサイトの統計情報の向上に必要な設定、購入、手数料、その他の情報を記憶および追跡する最も効率的な方法です。

使い方?

サーバーは、Cookieの形式で訪問者のブラウザにデータを送信します。 ブラウザはCookieを受け入れる場合があります。 存在する場合、訪問者のハードドライブにプレーンテキストレコードとして保存されます。 これで、訪問者がサイトの別のページに到達すると、ブラウザは同じCookieをサーバーに送信して取得します。 取得すると、サーバーは以前に保存されたものを認識または記憶します。 クッキーは5つの可変長フィールドのプレーンテキストデータレコードです-

  • 有効期限-Cookieの有効期限が切れる日付。 これが空白の場合、訪問者がブラウザを終了すると、Cookieは期限切れになります。
  • ドメイン-サイトのドメイン名。
  • Path -Cookieを設定するディレクトリまたはWebページへのパス。 任意のディレクトリまたはページからCookieを取得する場合、これは空白になる場合があります。
  • Secure -このフィールドに「secure」という単語が含まれている場合、Cookieはセキュアサーバーでのみ取得できます。 このフィールドが空白の場合、そのような制限はありません。
  • Name = Value -Cookieは、キーと値のペアの形式で設定および取得されます。

CookieはもともとCGIプログラミング用に設計されたもので、WebブラウザとWebサーバー間でCookieのデータが自動的に送信されるため、サーバー上のCGIスクリプトはクライアントに保存されたCookie値を読み書きできます。

VBScriptは、_Document_オブジェクトのcookieプロパティを使用してcookieを操作することもできます。 VBScriptは、現在のWebページに適用されるCookieを読み取り、作成、変更、および削除できます。

クッキーの保存

Cookieを作成する最も簡単な方法は、次のように_document.cookie_オブジェクトに文字列値を割り当てることです-

構文

document.cookie = "key1 = value1;key2 = value2;expires = date"

ここで、_expires_属性はオプションです。 この属性に有効な日付または時刻を指定すると、Cookieは指定された日付または時刻に期限切れになり、それ以降はCookieの値にアクセスできなくなります。

以下は、input cookieに顧客名を設定する例です。

<html>
   <head>
      <script type = "text/vbscript">
         Function WriteCookie
            If document.myform.customer.value = "" Then
               msgbox "Enter some value!"
            Else
               cookievalue = (document.myform.customer.value)
               document.cookie = "name = " + cookievalue
               msgbox "Setting Cookies : " & "name = " & cookievalue
            End If
         End Function
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

次の結果が生成されます。 テキストボックスに何かを入力し、「Set Cookie」ボタンを押してクッキーを設定します。

名前を入力:

現在、システムには_name_というCookieがあります。 コンマで区切られた複数の_key = value_ペアを使用して、複数のCookieを設定できます。 次のセクションで、このCookieの読み方を学びます。

クッキーを読む

_document.cookie_オブジェクトの値はCookieであるため、Cookieの読み取りは書き込みと同じくらい簡単です。 したがって、Cookieにアクセスする場合はいつでもこの文字列を使用できます。 _document.cookie_文字列は、セミコロンで区切られた_name = value_のペアのリストを保持します。_name_はCookieの_name_で、valueはその文字列値です。 次のように文字列をキーと値に分割するために、文字列の_split()_関数を使用できます-

以下は、前のセクションで設定されたクッキーを取得する例です-

<html>
   <head>
      <script type = "text/vbscript">
         Function ReadCookie
            allcookies = document.cookie
            msgbox "All Cookies : " + allcookies
            cookiearray = split(allcookies,";")

            For i = 0 to ubound(cookiearray)
               Name  = Split(cookiearray(i),"=")
               Msgbox "Key is : " + Name(0) + " and Value is : " + Name(1)
            Next
         End Function
      </script>
   </head>

   <body>
      <form name = "myform" action = "">
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>
   </body>
</html>

注意-ここで、_UBound_は_Array_クラスのメソッドであり、配列の長さを返します。 別の章で配列について説明します。その時まで、それを消化してみてください。

次の結果が生成されます。 次に、「Cookieを取得」ボタンを押して、前のセクションで設定したCookieを表示します。

注意-マシンにはすでに他のCookieが設定されている場合があります。 したがって、上記のコードは、マシンに設定されているすべてのCookieを表示します。

Cookieの有効期限の設定

有効期限を設定し、有効期限をCookie内に保存することにより、現在のブラウザーセッションを超えてCookieの寿命を延ばすことができます。 これは、_expires_属性に日付と時刻を設定することで実行できます。

次の例は、1か月後にCookieの有効期限を設定する方法を示しています-

<html>
   <head>
      <script type = "text/vbscript">
         Function WriteCookie()
            x = now()
            y = dateadd("m",1,now())  ' Making it to expire next
            cookievalue = document.myform.customer.value
            document.cookie = "name = "  & cookievalue
            document.cookie = "expires = " & y
            msgbox("Setting Cookies : " & "name=" & cookievalue )
         End Function
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

クッキーを削除する

場合によっては、Cookieを削除して、その後にCookieを読み取ろうとしても何も返されないようにすることがあります。 これを行うには、有効期限を過去の時間に設定するだけです。

次の例では、有効期限を1か月前に設定してCookieを削除する方法を示しています-

<html>
   <head>
      <script type = "text/vbscript">
         Function WriteCookie()
            x = now()
            x = now()
            a = Month(x)-1
            b = day(x)
            c = year(x)
            d = DateSerial(c,a,b)
            e = hour(x)

            msgbox e
            f = minute(x)

            msgbox f
            d = cdate(d & " " & e & ":" & f)

            msgbox d
            cookievalue = document.myform.customer.value
            document.cookie = "name = "  & cookievalue
            document.cookie = "expires = " & d
            msgbox("Setting Cookies : " & "name=" & cookievalue )
         End Function
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>
   </body>
</html>

VBScript-数字

数値関数は、開発者が効率的な方法で数値を処理するのに役立ち、サブタイプを変換するのにも役立ちます。 また、VBScriptに関連付けられた組み込みの数学関数を利用するのにも役立ちます。

数値変換関数

数値関数は、特定の数値をあるデータサブタイプから別のデータサブタイプに変換するのに役立ちます。

リンク:/vbscript/vbscript_number_conversion_functions [例を表示]

Sr.No Function & Description
1

CDbl

任意のバリアントサブタイプの指定された数をdoubleに変換する関数

2

CInt

任意のバリアントサブタイプの指定された数を整数に変換する関数

3

CLng

任意のバリアントサブタイプの指定された数をLongに変換する関数

4

CSng

任意のバリアントサブタイプの指定された数をシングルに変換する関数

5

Hex

任意のバリアントサブタイプの指定された数を16進数に変換する関数

数値フォーマット関数

数値書式設定関数は、開発者が指定した数値を希望する形式で表現するのに役立ちます。

リンク:/vbscript/vbscript_number_formatting_functions [例を表示]

Sr.No Function & Description
1

FormatNumber

数値としてフォーマットされた式を返す関数

2

FormatPercent

パーセンテージでフォーマットされた式を返す関数

数学関数

数学関数は、指定された入力数の数学関数および三角関数を評価するのに役立ちます。

リンク:/vbscript/vbscript_number_mathematical_functions [例を表示]

Sr.No Function & Description
1

Int

指定された数値の整数部分を返す関数

2

Fix

指定された数値の整数部分を返す関数

3

Log

指定された数値の自然対数を返す関数。 負の数は許可されません

4

Oct

指定されたパーセンテージの8進数値を返す関数

5

Hex

指定された数値の16進値を返す関数

6

Rnd

0〜1の乱数を返す関数

7

Sgn

指定された数値の符号に対応する数値を返す関数

8

Sqr

指定された数値の平方根を返す関数。 負の数は許可されません

9

Abs

指定された数値の絶対値を返す関数

10

Exp

指定された数に上げられたeの値を返す関数

11

Sin

指定された数値の正弦値を返す関数

12

Cos

指定された数値のコサイン値を返す関数

13

Tan

指定された数値の黄褐色の値を返す関数

VBScript-文字列

文字列は文字のシーケンスであり、アルファベットや数字、特殊文字、またはそれらすべてで構成できます。 変数は、二重引用符 ""で囲まれている場合、文字列と呼ばれます。

構文

variablename = "string"

str1 = "string"   ' Only Alphabets
str2 = "132.45"   ' Only Numbers
str3 = "!@#$;*"   ' Only Special Characters
Str4 = "Asc23@#"  ' Has all the above

文字列関数

開発者が文字列を非常に効果的に操作するのに役立つ、事前定義されたVBScript文字列関数があります。 以下は、VBScriptでサポートされているStringメソッドです。 詳細を知るには、それぞれの方法をクリックしてください。

Function Name Description
InStr Returns the first occurrence of the specified substring. Search happens from left to right.
InstrRev Returns the first occurrence of the specified substring. Search happens from Right to Left.
Lcase Returns the lower case of the specified string.
Ucase Returns the Upper case of the specified string.
Left Returns a specific number of characters from the left side of the string.
Right Returns a specific number of characters from the Right side of the string.
Mid Returns a specific number of characters from a string based on the specified parameters.
Ltrim Returns a string after removing the spaces on the left side of the specified string.
Rtrim Returns a string after removing the spaces on the right side of the specified string.
Trim Returns a string value after removing both leading and trailing blank spaces.
Len Returns the length of the given string.
Replace Returns a string after replacing a string with another string.
Space Fills a string with the specified number of spaces.
StrComp Returns an integer value after comparing the two specified strings.
String Returns a String with a specified character the specified number of times.
StrReverse Returns a String after reversing the sequece of the characters of the given string.

VBScript-配列

配列とは何ですか?

変数は値を格納するコンテナであることをよく知っています。 開発者は、一度に1つの変数に複数の値を保持できる場合があります。 一連の値が単一の変数に格納される場合、それは「配列変数」と呼ばれます。

配列宣言

配列は、変数の宣言と同じ方法で宣言されますが、配列変数の宣言では括弧が使用されます。 次の例では、配列のサイズが括弧内に記載されています。

'Method 1 : Using Dim
Dim arr1() 'Without Size

'Method 2 : Mentioning the Size
Dim arr2(5) 'Declared with size of 5

'Method 3 : using 'Array' Parameter
Dim arr3
arr3 = Array("apple","Orange","Grapes")
  • 配列サイズは5と示されていますが、配列インデックスがゼロから始まるため、6つの値を保持できます。
  • 配列インデックスを負にすることはできません。
  • VBScript配列は、任意のタイプの変数を配列に格納できます。 したがって、配列は整数、文字列、または文字を単一の配列変数に格納できます。

配列への値の割り当て

割り当てられる値のそれぞれに対して配列インデックス値を指定することにより、値が配列に割り当てられます。 文字列にすることができます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim arr(5)
         arr(0) = "1"            'Number as String
         arr(1) = "VBScript"     'String
         arr(2) = 100            'Number
         arr(3) = 2.45           'Decimal Number
         arr(4) = #10/07/2013#   'Date
         arr(5) = #12.45 PM#     'Time

         document.write("Value stored in Array index 0 : " & arr(0) & "<br/>")
         document.write("Value stored in Array index 1 : " & arr(1) & "<br/>")
         document.write("Value stored in Array index 2 : " & arr(2) & "<br/>")
         document.write("Value stored in Array index 3 : " & arr(3) & "<br/>")
         document.write("Value stored in Array index 4 : " & arr(4) & "<br/>")
         document.write("Value stored in Array index 5 : " & arr(5) & "<br/>")

      </script>
   </body>
</html>

上記のコードが.HTMLとして保存され、Internet Explorerで実行されると、次の結果が生成されます-

Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Value stored in Array index 2 : 100
Value stored in Array index 3 : 2.45
Value stored in Array index 4 : 7/10/2013
Value stored in Array index 5 : 12:45:00 PM

多次元配列

配列は、単一の次元に限定されず、最大60次元を持つことができます。 2次元配列は、最も一般的に使用されるものです。

次の例では、3行4列の多次元配列が宣言されています。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim arr(2,3)   ' Which has 3 rows and 4 columns
         arr(0,0) = "Apple"
         arr(0,1) = "Orange"
         arr(0,2) = "Grapes"
         arr(0,3) = "pineapple"

         arr(1,0) = "cucumber"
         arr(1,1) = "beans"
         arr(1,2) = "carrot"
         arr(1,3) = "tomato"

         arr(2,0) = "potato"
         arr(2,1) = "sandwitch"
         arr(2,2) = "coffee"
         arr(2,3) = "nuts"

         document.write("Value in Array index 0,1 : " &  arr(0,1) & "<br/>")
         document.write("Value in Array index 2,2 : " &  arr(2,2) & "<br/>")

      </script>
   </body>
</html>

上記のコードが.HTMLとして保存され、Internet Explorerで実行されると、次の結果が生成されます-

Value stored in Array index : 0 , 1 : Orange
Value stored in Array index : 2 , 2 : coffee

Redimステートメント

ReDimステートメントは、動的配列変数を宣言し、ストレージスペースを割り当てまたは再割り当てするために使用されます。

ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
  • Preserve -最後の次元のサイズを変更するときに既存の配列のデータを保持するために使用されるオプションのパラメーター。
  • varname -変数の名前を示す必須パラメータ。標準の変数命名規則に従う必要があります。
  • subscripts -配列のサイズを示す必須パラメーター。

以下の例では、配列の既存のサイズが変更されたときに、配列が再定義され、値が保持されています。

-元よりも小さい配列のサイズを変更すると、削除された要素のデータは失われます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim a()
         i = 0
         redim a(5)
         a(0) = "XYZ"
         a(1) = 41.25
         a(2) = 22

         REDIM PRESERVE a(7)
         For i = 3 to 7
         a(i) = i
         Next

         'to Fetch the output
         For i = 0 to ubound(a)
            Msgbox a(i)
         Next
      </script>
   </body>
</html>

上記のスクリプトをHTMLとして保存し、Internet Explorerで実行すると、次の結果が生成されます。

XYZ
41.25
22
3
4
5
6
7

配列メソッド

VBScriptには、開発者が配列を効果的に処理するのに役立つさまざまな組み込み関数があります。 配列と組み合わせて使用​​されるすべてのメソッドを以下にリストします。 詳細を知るには、メソッド名をクリックしてください。

Function Description
LBound A Function, which returns an integer that corresponds to the smallest subscript of the given arrays.
UBound A Function, which returns an integer that corresponds to the Largest subscript of the given arrays.
Split A Function, which returns an array that contains a specified number of values. Splitted based on a Delimiter.
Join A Function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method.
Filter A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria.
IsArray A Function, which returns a boolean value that indicates whether or not the input variable is an array.
Erase A Function, which recovers the allocated memory for the array variables.

VBScript-日付と時刻の関数

VBScriptの日付と時刻の関数は、開発者が日付と時刻をある形式から別の形式に変換したり、特定の条件に合った形式で日付または時刻の値を表現したりするのに役立ちます。

日付関数

Function Description
Date A Function, which returns the current system date
CDate A Function, which converts a given input to Date
DateAdd A Function, which returns a date to which a specified time interval has been added
DateDiff A Function, which returns the difference between two time period
DatePart A Function, which returns a specified part of the given input date value
DateSerial A Function, which returns a valid date for the given year,month and date
FormatDateTime A Function, which formats the date based on the supplied parameters
IsDate A Function, which returns a Boolean Value whether or not the supplied parameter is a date
Day A Function, which returns an integer between 1 and 31 that represents the day of the specified Date
Month A Function, which returns an integer between 1 and 12 that represents the month of the specified Date
Year A Function, which returns an integer that represents the year of the specified Date
MonthName A Function, which returns Name of the particular month for the specified date
WeekDay A Function, which returns an integer(1 to 7) that represents the day of the week for the specified day.
WeekDayName A Function, which returns the weekday name for the specified day.

時間関数

Function Description
Now A Function, which returns the current system date and Time
Hour A Function, which returns and integer between 0 and 23 that represents the Hour part of the the given time
Minute A Function, which returns and integer between 0 and 59 that represents the Minutes part of the the given time
Second A Function, which returns and integer between 0 and 59 that represents the Seconds part of the the given time
Time A Function, which returns the current system time
Timer A Function, which returns the number of seconds and milliseconds since 12:00 AM
TimeSerial A Function, which returns the time for the specific input of hour,minute and second
TimeValue A Function, which converts the input string to a time format

VBScript-手順

関数とは何ですか?

関数は、プログラム内のどこからでも呼び出すことができる再利用可能なコードのグループです。 これにより、同じコードを何度も記述する必要がなくなります。 これにより、プログラマは大きなプログラムをいくつかの小さくて管理可能な機能に分割できます。 組み込み関数とは別に、VBScriptではユーザー定義関数も作成できます。 このセクションでは、VBScriptで独自の関数を作成する方法について説明します。

関数定義

関数を使用する前に、その特定の関数を定義する必要があります。 VBScriptで関数を定義する最も一般的な方法は、Functionキーワードを使用し、その後に一意の関数名を使用することです。これは、パラメーターのリストと、関数。

基本的な構文は以下に示されています-

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Function Functionname(parameter-list)
            statement 1
            statement 2
            statement 3
            .......
            statement n
         End Function

      </script>
   </body>
</html>

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Function sayHello()
            msgbox("Hello there")
         End Function

      </script>
   </body>
</html>

関数を呼び出す

スクリプトのどこかで関数を呼び出すには、 Call キーワードを使用してその関数の名前を簡単に記述する必要があります。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Function sayHello()
            msgbox("Hello there")
         End Function

         Call sayHello()

      </script>
   </body>
</html>

関数パラメーター

これまで、パラメーターのない関数を見てきましたが、関数を呼び出すときに異なるパラメーターを渡す機能があります。 これらの渡されたパラメーターは関数内でキャプチャーでき、これらのパラメーターに対して任意の操作を実行できます。 関数は、 Call キーワードを使用して呼び出されます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Function sayHello(name, age)
            msgbox( name & " is " & age & " years old.")
         End Function

         Call sayHello("Tutorials point", 7)

      </script>
   </body>
</html>

関数から値を返す

VBScript関数には、オプションのreturnステートメントを含めることができます。 これは、関数から値を返す場合に必要です。 たとえば、関数に2つの数値を渡すと、関数から呼び出し元プログラムで乗算を返すことが期待できます。

-関数は、関数名自体に割り当てられた配列として、コンマで区切られた複数の値を返すことができます。

この関数は2つのパラメーターを受け取り、それらを連結して、呼び出し元プログラムに結果を返します。 VBScriptでは、関数名を使用して関数から値が返されます。 2つ以上の値を返す場合は、関数名が値の配列とともに返されます。 呼び出し側プログラムでは、結果は結果変数に保存されます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Function concatenate(first, last)
            Dim full
            full = first & last
            concatenate = full  'Returning the result to the function name itself
         End Function

      </script>
   </body>
</html>

今、私たちは次のようにこの関数を呼び出すことができます-

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Function concatenate(first, last)
            Dim full
            full = first & last
            concatenate = full  'Returning the result to the function name itself
         End Function
         ' Here is the usage of returning value from  function.
         dim result
            result = concatenate("Zara", "Ali")
        msgbox(result)
      </script>
   </body>
</html>

サブ手順

サブ手順は関数に似ていますが、違いはほとんどありません。

  • サブプロシージャは値を返しませんが、関数は値を返す場合と返さない場合があります。
  • サブプロシージャcallキーワードなしで呼び出すことができます。
  • サブプロシージャは常に Sub および End Sub ステートメントで囲まれます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Sub sayHello()
            msgbox("Hello there")
         End Sub

      </script>
   </body>
</html>

呼び出し手順

スクリプトのどこかでプロシージャを呼び出すには、 Call キーワードを使用して、または使用せずにそのプロシージャの名前を記述するだけで済みます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Sub sayHello()
            msgbox("Hello there")
         End Sub
         sayHello()

      </script>
   </body>
</html>

関数の高度な概念

VBScript関数について学ぶべきことがたくさんあります。 パラメータbyvalueまたはbyreferenceを渡すことができます。 詳細については、それぞれをクリックしてください。

  • link:/vbscript/vbscript_byvalue_function [ByVal-パラメータを値で渡す]
  • link:/vbscript/vbscript_byref_function [ByRef-パラメータを参照で渡す]

VBScript-ダイアログボックス

ダイアログボックスとは何ですか?

VBScriptを使用すると、開発者はユーザーと効果的に対話できます。 ユーザーにメッセージを表示するメッセージボックス、またはユーザーが値を入力できる入力ボックスを使用できます。

VBScript MsgBox関数

MsgBox関数はメッセージボックスを表示し、ユーザーがボタンをクリックするのを待機します。その後、ユーザーがクリックしたボタンに基づいてアクションが実行されます。

構文

MsgBox(prompt[,buttons][,title][,helpfile,context])

パラメータ説明

  • プロンプト-必須パラメーター。 ダイアログボックスにメッセージとして表示される文字列。 プロンプトの最大長は約1024文字です。 メッセージが1行を超える場合、キャリッジリターン文字(Chr(13))または改行文字(Chr(10))を使用して各行を区切ることができます。
  • ボタン-オプションのパラメータ。 表示するボタンのタイプ、使用するアイコンスタイル、デフォルトボタンのID、およびメッセージボックスのモダリティを指定する数値式。 空白のままにすると、ボタンのデフォルト値は0です。
  • タイトル-オプションのパラメーター。 ダイアログボックスのタイトルバーに表示される文字列式。 タイトルを空白のままにすると、アプリケーション名がタイトルバーに配置されます。
  • helpfile -オプションのパラメーター。 ダイアログボックスの状況依存ヘルプを提供するために使用するヘルプファイルを識別する文字列式。
  • context -オプションのパラメーター。 ヘルプ作成者が適切なヘルプトピックに割り当てたヘルプコンテキスト番号を識別する数値式。 コンテキストが提供される場合、ヘルプファイルも提供する必要があります。
  • ボタン*パラメータは、次の値のいずれかを取ることができます-
  • 0 vbOKOnly OKボタンのみを表示します。
  • 1 vbOKCancel [OK]ボタンと[キャンセル]ボタンを表示します。
  • 2 vbAbortRetryIgnore中止、再試行、および無視ボタンを表示します。
  • 3 vbYesNoCancel [はい]、[いいえ]、および[キャンセル]ボタンを表示します。
  • 4 vbYesNo [はい]および[いいえ]ボタンを表示します。
  • 5 vbRetryCancel [再試行]および[キャンセル]ボタンを表示します。
  • 16 vbCriticalクリティカルメッセージアイコンを表示します。
  • 32 vbQuestion警告クエリアイコンを表示します。
  • 48 vbExclamation警告メッセージアイコンを表示します。
  • 64 vbInformation情報メッセージアイコンを表示します。
  • 0 vbDefaultButton1最初のボタンはデフォルトです。
  • 256 vbDefaultButton2 2番目のボタンがデフォルトです。
  • 512 vbDefaultButton3 3番目のボタンはデフォルトです。
  • 768 vbDefaultButton4 4番目のボタンがデフォルトです。
  • 0 vbApplicationModalアプリケーションモーダル。 ユーザーがメッセージボックスに応答するまで、現在のアプリケーションは動作しません。
  • 4096 vbSystemModalシステムモーダル。 ユーザーがメッセージボックスに応答するまで、すべてのアプリケーションは動作しません。

上記の値は、論理的に4つのグループに分けられます。最初のグループ(0〜5)は、メッセージボックスに表示されるボタンを示します。 2番目のグループ(16、32、48、64)は表示されるアイコンのスタイルを示し、3番目のグループ(0、256、512、768)はどのボタンをデフォルトにする必要があるかを示し、4番目のグループ(0、4096 )メッセージボックスのモダリティを決定します。

戻り値

MsgBox関数は、次の値のいずれかを返すことができます-

  • 1-vbOK-[OK]がクリックされた
  • 2-vbCancel-キャンセルがクリックされた
  • 3-vbAbort-中止がクリックされた
  • 4-vbRetry-再試行がクリックされた
  • 5-vbIgnore-無視がクリックされた
  • 6-vbはい-はいがクリックされました
  • 7-vbNo-いいえがクリックされました

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         'Message Box with just prompt message
         MsgBox("Welcome")

         'Message Box with title, yes no and cancel Butttons
         a = MsgBox("Do you like blue color?",3,"Choose options")
         ' Assume that you press No Button
         document.write("The Value of a is " & a)

      </script>
   </body>
</html>

上記のスクリプトが実行されると、メッセージボックスが表示され、[いいえ]ボタンを押すと、aの値は7になります。

The Value of a is 7

VBScript InputBox関数

InputBox関数は、ユーザーがユーザーから値を取得するのに役立ちます。 値を入力した後、ユーザーが[OK]ボタンをクリックするか、キーボードのEnterキーを押すと、InputBox関数はテキストボックス内のテキストを返します。 ユーザーが[キャンセル]ボタンをクリックすると、関数は空の文字列( "")を返します。

構文

InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])

パラメータ説明

  • プロンプト-必須パラメーター。 ダイアログボックスにメッセージとして表示される文字列。 プロンプトの最大長は約1024文字です。 メッセージが1行を超える場合、キャリッジリターン文字(Chr(13))または改行文字(Chr(10))を使用して各行を区切ることができます。
  • タイトル-オプションのパラメーター。 ダイアログボックスのタイトルバーに表示される文字列式。 タイトルを空白のままにすると、アプリケーション名がタイトルバーに配置されます。
  • デフォルト-オプションのパラメータ。 ユーザーが表示したいテキストボックス内のデフォルトのテキスト。
  • XPos -オプションのパラメーター。 画面の左側から水平方向へのプロンプト距離を表すX軸の位置。 空白のままにすると、入力ボックスは水平方向の中央に配置されます。
  • YPos -オプションのパラメーター。 画面の左側から垂直方向へのプロンプト距離を表すY軸の位置。 空白のままにすると、入力ボックスは垂直方向の中央に配置されます。
  • helpfile -オプションのパラメーター。 ダイアログボックスの状況依存ヘルプを提供するために使用するヘルプファイルを識別する文字列式。
  • context -オプションのパラメーター。 ヘルプ作成者が適切なヘルプトピックに割り当てたヘルプコンテキスト番号を識別する数値式。 コンテキストが提供される場合、ヘルプファイルも提供する必要があります。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         ' Input Box with only Prompt
         InputBox("Enter a number")

         ' Input Box with a Title
         a = InputBox("Enter a Number","Enter Value")
         msgbox a

         ' Input Box with a Prompt,Title and Default value
         a = InputBox("Enter a Number","Enter Value",123)
         msgbox a

         ' Input Box with a Prompt,Title,Default and XPos
         a = InputBox("Enter your name","Enter Value",123,700)
         msgbox a

         ' Input Box with a Prompt,Title and Default and YPos
         a = InputBox("Enter your name","Enter Value",123,,500)
         msgbox a

      </script>
   </body>
</html>

上記のスクリプトを実行すると、入力ボックスが表示され、ユーザーが入力した値が表示されます。

オブジェクト指向のVBScript

オブジェクトとは

VBScriptランタイムオブジェクトは、さまざまなタスクを実行するのに役立ちます。 このセクションは、オブジェクトをインスタンス化して操作する方法を理解するのに役立ちます。

構文

オブジェクトをシームレスに操作するには、オブジェクトを宣言し、 Set キーワードを使用してインスタンス化する必要があります。

Dim objectname    'Declare the object name
Set objectname = CreateObject(object_type)

以下の例では、 Scripting.Dictionary 型のオブジェクトを作成しています。

Dim obj
Set obj = CreateObject("Scripting.Dictionary")

オブジェクトの破棄

オブジェクトを破壊する意義は、メモリを解放し、オブジェクト変数をリセットすることです。

構文

オブジェクトを破棄するには、 Set キーワードに続いてオブジェクト名を使用し、 Nothing をポイントする必要があります。

Set objectname = Nothing 'Destroy the object.

以下の例では、 Scripting.Dictionary 型のオブジェクトを作成しています。

Dim obj
Set obj = CreateObject("Scripting.Dictionary")
Set obj = Nothing.

オブジェクトの使用

詳細については、指定されたオブジェクトタイプのそれぞれをクリックしてください。

オブジェクトタイプ

説明

リンク:/vbscript/vbscript_class_objects [クラス]

クラスはコンテナであり、それに関連付けられ、Type Classのオブジェクトを作成することによりアクセスされるメソッドと変数を保持します。

リンク:/vbscript/vbscript_fso_objects [Scripting.FileSystemObject]

これは、ファイルシステムを操作できるオブジェクトのグループです。

リンク:/vbscript/vbscript_dictionary_objects [Scripting.Dictionary]

辞書オブジェクトの作成に使用されるオブジェクトのグループ。

リンク:/vbscript/vbscript_debug_objects [Debug]

Microsoftスクリプトデバッガーに出力を送信できるグローバルオブジェクト。

VBScript-正規表現

正規表現は、パターンを形成する一連の文字であり、主に検索と置換に使用されます。 パターンを作成する目的は、特定の文字列を照合することで、開発者は条件に基づいて文字を抽出し、特定の文字を置き換えることができます。

RegExpオブジェクト

RegExpオブジェクトは、開発者が文字列のパターンを一致させるのに役立ち、プロパティとメソッドは正規表現を簡単に操作するのに役立ちます。 JavaScriptのRegExpに似ています

プロパティ

  • Pattern -Patternメソッドは、正規表現を定義するために使用される文字列を表し、正規表現オブジェクトを使用する前に設定する必要があります。
  • IgnoreCase -trueまたはfalseの場合、文字列内のすべての可能な一致に対して正規表現をテストする必要があるかどうかを表すブールプロパティ。 明示的に指定されていない場合、IgnoreCase値はFalseに設定されます。
  • Global -文字列内のすべての可能な一致に対して正規表現をテストする必要があるかどうかを表すブールプロパティ。 明示的に指定されていない場合、グローバル値はFalseに設定されます。

方法

  • Test (search-string)-Testメソッドは引数として文字列を受け取り、正規表現が文字列と正常に一致する場合はTrueを返し、そうでない場合はFalseを返します。
  • Replace (search-string、replace-string)-Replaceメソッドは2つのパラメーターを取ります。 検索が成功すると、その一致をreplace-stringに置き換え、新しい文字列が返されます。 一致するものがない場合、元の検索文字列が返されます。
  • Execute (search-string)-ExecuteメソッドはReplaceと同様に機能しますが、成功した各マッチのMatchオブジェクトを含むMatchesコレクションオブジェクトを返す点が異なります。 元の文字列は変更されません。

コレクションオブジェクトに一致

Matchesコレクションオブジェクトは、Executeメソッドの結果として返されます。 このコレクションオブジェクトには、0個以上のMatchオブジェクトを含めることができ、このオブジェクトのプロパティは読み取り専用です。

  • Count -Countメソッドは、コレクション内の一致オブジェクトの数を表します。
  • Item -Itemメソッドを使用すると、matchesコレクションオブジェクトからmatchオブジェクトにアクセスできます。

一致オブジェクト

Matchオブジェクトは、matchesコレクションオブジェクト内に含まれています。 これらのオブジェクトは、文字列の検索後の一致の成功を表します。

  • FirstIndex -一致が発生した元の文字列内の位置を表します。 このインデックスはゼロベースです。つまり、文字列の最初の位置は0です。
  • 長さ-一致した文字列の全長を表す値。
  • -一致した値またはテキストを表す値。 また、Matchオブジェクトにアクセスするときのデフォルト値です。

パターンパラメーターについて

パターンの構築はPERLに似ています。 正規表現を使用する場合、パターンの構築が最も重要です。 このセクションでは、さまざまな要因に基づいてパターンを作成する方法を扱います。

位置合わせ

位置一致の重要性は、正規表現を正しい場所に配置することです。

Symbol Description
^ Matches only the beginning of a string.
$ Match only the end of a string.
\b Matches any word boundary
\B Matches any non-word boundary

リテラルマッチング

アルファベット、数字、特殊文字、または10進数、16進数などの任意の形式の文字をリテラルとして扱うことができます。 正規表現のコンテキスト内ですでに特別な意味を持つ文字はほとんどないため、エスケープシーケンスを使用してエスケープする必要があります。

Symbol Description
Alphanumeric Matches alphabetical and numerical characters only.
\n Matches a new line.
\[ Matches [ literal only
\] Matches ] literal only
\( Matches ( literal only
\) Matches ) literal only
\t Matches horizontal tab
\v Matches vertical tab
Matches
literal only \\{
Matches \{ literal only \}
Matches } literal only \\
Matches \ literal only \?
Matches ? literal only \ *
Matches* literal only \+
Matches + literal only \.
Matches . literal only \b
Matches any word boundary \B
Matches any non-word boundary \f
Matches a form feed \r
Matches carriage return \xxx
Matches the ASCII character of an octal number xxx. \xdd
Matches the ASCII character of an hexadecimal number dd. \uxxxx

一致する文字クラス

文字クラスは、カスタマイズされたグループ化によって形成され、[]括弧で囲まれたパターンです。 リストに含まれてはならない文字クラスを想定している場合は、キャップ^である負の記号を使用して特定の文字クラスを無視する必要があります。

Symbol Description
[xyz] Match any of the character class enclosed within the character set.
[^xyz] Matches any of the character class that are NOT enclosed within the character set.
. Matches any character class except \n
\w Match any word character class. Equivalent to [a-zA-Z_0-9]
\W Match any non-word character class. Equivalent to [^a-zA-Z_0-9]
\d Match any digit class. Equivalent to [0-9].
\D Match any non-digit character class. Equivalent to [^0-9].
\s Match any space character class. Equivalent to [ \t\r\n\v\f]
\S Match any space character class. Equivalent to [^\t\r\n\v\f]

繰り返しマッチング

繰り返し一致により、正規表現内で複数の検索が可能になります。 また、正規表現で要素が繰り返される回数も指定します。

Symbol Description
* Matches zero or more occurrences of the given regular Expression. Equivalent to \{0,}.
+ Matches one or more occurrences of the given regular Expression. Equivalent to \{1,}.
? Matches zero or one occurrences of the given regular Expression. Equivalent to \{0,1}.
{x} Matches exactly x number of occurrences of the given regular expression.
\{x,} Match atleast x or more occurrences of the given regular expression.
\{x,y} Matches x to y number of occurences of the given regular expression.

交替とグループ化

交替とグループ化により、開発者は、正規表現内の複雑な句を処理する際に、より複雑な正規表現を作成でき、柔軟性と制御性が向上します。

Symbol Description
0 Grouping a clause to create a clause. "(xy)?(z)" matches "xyz" or "z".
Alternation combines one regular expression clause and then matches any of the individual clauses. "(ij) (23)

正規表現の構築

以下に、正規表現の作成方法を明確に説明するいくつかの例を示します。

Regular Expression Description
"^\s*.." and "..\s*$" Represents that there can be any number of leading and trailing space characters in a single line.
"((\$\s?) (#\s?))?"
Represents an optional $ or # sign followed by an optional space. "\d+(\.(\d\d)?)?\d+(\.(\d\d)?)?"

以下の例は、ユーザーが、@が続き、その後にドメイン名が続くメールIDが存在するような形式に一致するメールIDを入力したかどうかをチェックします。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         strid = "[email protected]"
         Set re = New RegExp
         With re
            .Pattern    = "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"
            .IgnoreCase = False
            .Global     = False
         End With

         ' Test method returns TRUE if a match is found
         If re.Test( strid ) Then
            Document.write(strid & " is a valid e-mail address")
         Else
            Document.write(strid & " is NOT a valid e-mail address")
         End If

        Set re = Nothing
      </script>
   </body>
</html>

VBScript-エラー処理

プログラミングには、(a)構文エラー、(b)ランタイムエラー、(c)論理エラーの3種類のエラーがあります。

構文エラー

構文エラーは解析エラーとも呼ばれ、VBScriptの解釈時に発生します。 たとえば、次の行は閉じ括弧が欠落しているため、構文エラーが発生します-

<script type = "text/vbscript">

   dim x,y
   x = "finddevguides"
   y = Ucase(x

</script>

ランタイムエラー

ランタイムエラーは、例外とも呼ばれ、実行中に解釈後に発生します。 たとえば、ここの構文は正しいが、実行時に存在しない関数であるfnmultiplyを呼び出そうとしているため、次の行は実行時エラーを引き起こします-

<script type = "text/vbscript">
   Dim x,y
   x = 10
   y = 20
   z = fnadd(x,y)
   a = fnmultiply(x,y)

   Function fnadd(x,y)
      fnadd = x+y
   End Function

</script>

論理エラー

論理エラーは、追跡が最も難しいタイプのエラーです。 これらのエラーは、構文エラーまたは実行時エラーの結果ではありません。 代わりに、スクリプトを駆動するロジックを間違えたときに発生し、期待した結果が得られません。 これらのエラーをキャッチすることはできません。これは、ビジネス要件によってプログラムにどのタイプのロジックを配置するかによって異なるためです。 たとえば、数値をゼロで除算したり、無限ループに入るスクリプトを記述したりします。

エラーオブジェクト

Aランタイムエラーが発生した場合、エラーメッセージを表示して実行を停止します。 開発者として、エラーをキャプチャする場合は、 Error オブジェクトが使用されます。

以下の例では、 Err.Number はエラー番号を示し、 Err.Description はエラーの説明を示します。

<script type = "text/vbscript">

  Err.Raise 6     ' Raise an overflow error.
  MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
  Err.Clear       ' Clear the error.

</script>

VBScriptのその他のステートメント

VBScriptには、開発者が効率的なスクリプトを開発するのに役立つ他の重要なステートメントがいくつかあります。 次の表に、このような重要なステートメントのセットを示します。 この章では、これらの各ステートメントを例とともに詳細に説明します。

Category Function Name/Statement Name
Options Option Explicit
Script Engine ID ScriptEngine
variants IsArray, IsEmpty, IsNull, IsNumeric, IsObject, TypeName
Expression Eval,Execute
Control Statement With…​End With
Math Function Randomize

明示的なオプション

*Option Explicit* は、コードの一部で使用される前に、開発者が *Dim* ステートメントを使用して変数を宣言することを強制します。

構文

Option Explicit

*Option Explicit* を使用し、変数を宣言しない場合、インタープリターはエラーをスローします。
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Option Explicit
         Dim x,y,z,a
         x = 10
         y = 20
         z = fnadd(x,y)
         a = fnmultiply(x,y)

         Function fnadd(x,y)
            fnadd = x+y
         End Function

      </script>
   </body>
</html>

ScriptEngine

*ScriptEngine* は、使用中のスクリプト言語の詳細を表します。 また、vScriptスクリプトのメジャーバージョン、vbscriptエンジンのマイナーバージョン、vbscriptのビルドバージョンをそれぞれ提供する *ScriptEngineMajorVersion、ScriptEngineMinorバージョン、ScriptEngineBuildVersion* と組み合わせて使用​​されます。

構文

ScriptEngine

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim scriptdetails
         scriptdetails =  " Version " & ScriptEngine & " - "
         'For getting Major version, use ScriptEngineMajorVersion'

         scriptdetails = scriptdetails &  ScriptEngineMajorVersion & "."

         'For getting Minor version, use ScriptEngineMinorVersion'
         scriptdetails = scriptdetails & ScriptEngineMinorVersion & "."

         'For getting Build version, use ScriptEngineBuildVersion'
         scriptdetails = scriptdetails & ScriptEngineBuildVersion

         Document.write scriptdetails

      </script>
   </body>
</html>

IEでスクリプトを実行するときに拡張子lのファイルを保存すると、次の結果が画面に表示されます。

Version VBScript - 5.8.16996

IsEmpty

関数IsEmptyは、式が空かどうかを確認するために使用されます。 ブール値を返します。 IsEmpty は、変数が初期化されていないか、明示的に空に設定されている場合にTrueを返します。 それ以外の場合、式はFalseを返します。

構文

IsEmpty(expression)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim var, MyCheck
         MyCheck = IsEmpty(var)
         Document.write "Line 1 : " & MyCheck & "<br/>"

         var = Null   ' Assign Null.
         MyCheck = IsEmpty(var)
         Document.write "Line 2 : " & MyCheck & "<br/>"

         var = Empty   ' Assign Empty.
         MyCheck = IsEmpty(var)
         Document.write "Line 3 : " & MyCheck & "<br/>"

      </script>
   </body>
</html>

IEでスクリプトを実行するときにl拡張子を付けてファイルを保存すると、次の結果が画面に表示されます。

Line 1 : True
Line 2 : False
Line 3 : True

無効です

関数IsNullは、式に有効なデータがあるかどうかを確認するために使用されます。 ブール値を返します。 IsNull は、変数がNullの場合Trueを返します。それ以外の場合、式はFalseを返します。

構文

IsNull(expression)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim var, res
         res = IsNull(var)
         document.write "Line 1 : " & res & "<br/>"

         var = Null
         res = IsNull(var)
         document.write "Line 2 : " & res & "<br/>"

         var = Empty
         res = IsNull(var)
         document.write "Line 3 : " & res & "<br/>"

      </script>
   </body>
</html>

IEでスクリプトを実行するときにl拡張子を付けてファイルを保存すると、次の結果が画面に表示されます。

Line 1 : False
Line 2 : True
Line 3 : False

IsObject

IsObject関数は、式に有効なオブジェクトがあるかどうかを確認するために使用されます。 ブール値を返します。 IsObject は、式にオブジェクトサブタイプが含まれる場合はTrueを返し、そうでない場合は式はFalseを返します。

構文

IsObject(expression)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
        Dim fso,b
        b = 10
        set fso = createobject("Scripting.Filesystemobject")

        x = isobject(fso)
        Document.write "Line 1 : " &  x  & "<br/>"

        y = isobject(b)
        Document.write "Line 2 : " &  y  & "<br/>"

      </script>
   </body>
</html>

IEでスクリプトを実行するときにl拡張子を付けてファイルを保存すると、次の結果が画面に表示されます。

Line 1 : True
Line 2 : False

IsNumeric

IsNumeric関数は、式に数値サブタイプがあるかどうかを確認するために使用されます。 ブール値を返します。 IsObject は、式に数値サブタイプが含まれている場合はTrueを返し、そうでない場合はFalseを返します。

構文

IsNumeric(expression)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim var, chk
         var = 20
         chk = IsNumeric(var)
         Document.write "Line 1 : " &  chk  & "<br/>"

         var = "3.1415935745"
         chk = IsNumeric(var)
         Document.write "Line 2 : " &  chk  & "<br/>"

         var = "20 Chapter 23.123 VBScript"
         chk = IsNumeric(var)
         Document.write "Line 3 : " &  chk  & "<br/>"

      </script>
   </body>
</html>

IEでスクリプトを実行するときに拡張子lのファイルを保存すると、次の結果が画面に表示されます。

Line 1 : True
Line 2 : True
Line 3 : False

TypeName

TypeName関数は、変数のバリアントサブタイプ情報を返すために使用されます。

構文

TypeName(varname)

Typename関数は、次の値のいずれかを返すことができます。

  • バイト-バイト値
  • 整数-整数値
  • 長-長整数値
  • 単一-単精度浮動小数点値
  • Double-倍精度の浮動小数点値
  • 通貨-通貨価値
  • 10進数-10進数値
  • 日付-日付または時刻の値
  • 文字列-文字列値
  • ブール-ブール値
  • 空-初期化されていない値
  • Null-有効なデータなし
  • オブジェクト-オブジェクトのタイプ名
  • なし-オブジェクトインスタンスをまだ参照していないオブジェクト変数 *エラー

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim ArrVar(2), vartype
         NullVar = Null   ' Assign Null value.

         vartype = TypeName(3.1450)
         Document.write "Line 1 : " &  vartype  & "<br/>"

         vartype = TypeName(432)
         Document.write "Line 2 : " &  vartype  & "<br/>"

         vartype = TypeName("Microsoft")
         Document.write "Line 3 : " &  vartype  & "<br/>"

         vartype = TypeName(NullVar)
         Document.write "Line 4 : " &  vartype  & "< br/>"

         vartype = TypeName(ArrVar)
         Document.write "Line 5 : " &  vartype  & "<br/>"

      </script>
   </body>
</html>

IEでスクリプトを実行するときにl拡張子を付けてファイルを保存すると、次の結果が画面に表示されます。

Line 1 : Double
Line 2 : Integer
Line 3 : String
Line 4 : Null
Line 5 : Variant()

Eval

Eval関数は式を実行し、結果を文字列または数値として返します。

構文

Eval(expression)

引数Expressionは、文字列式または数値にすることができます。 Eval関数に、数値式または関数名を含まず、単純なテキスト文字列のみを含む文字列を渡すと、実行時エラーが発生します。 たとえば、Eval( "VBScript")はエラーになります。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Document.write Eval("10 + 10") & "<br/>"
         Document.write Eval("101 = 200") & "<br/>"
         Document.write Eval("5* 3") & "<br/>"

      </script>
   </body>
</html>

IEでスクリプトを実行するときにl拡張子を付けてファイルを保存すると、次の結果が画面に表示されます。

20
false
15

実行する

Executeステートメントは、実行用の1つ以上のステートメントを含む文字列式である引数を受け入れます。

構文

Execute(expression)

VBScriptでは、a = bは2つの方法で解釈できます。 xの値がyに割り当てられている割り当てステートメントとして扱うことができます。 また、aとbの値が同じかどうかをテストする式として解釈することもできます。 一致する場合、結果はTrueです。そうでない場合、結果はFalseです。 Executeステートメントは常に最初の解釈を使用し、Evalステートメントは常に2番目の解釈を使用します。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim x
         x = "Global"
         y = "VBScript"
         Execute("x = y")

         msgbox x
         msgbox y

      </script>
   </body>
</html>

IEでスクリプトを実行するときにl拡張子を付けてファイルを保存すると、次の結果が画面に表示されます。

VBScript
VBScript

With..End With

Withステートメントを使用すると、オブジェクト名を何度も明示的に言及することなく、指定したオブジェクトに対して一連の操作を実行できます。

構文

With (objectname)
   statement 1
   statement 2
   statement 3
   ...
   ...
   statement n
End With

次のスクリプトを実行すると、Winwordが開き、指定されたテキストが入力されます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Msg =  "Vbscript" & vbCrLf & "Programming"
         Set objWord = CreateObject("Word.Application")
         objWord.Visible = True

         ' Objects methods are accessed without requaliyfying the objects again.'
         With objWord
            .Documents.Add
            .Selection.TypeText Msg
            .Selection.WholeStory
         End With

      </script>
   </body>
</html>

ランダム化

Randomizeステートメントは、開発者が乱数を生成するのに役立つ乱数ジェネレーターを初期化します。

構文

Randomize [number]

次のスクリプトを実行すると、Winwordが開き、指定されたテキストが入力されます。

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim MyValue
         Randomize
         MyValue = Int((100 * Rnd) + 1)   ' Generate random value between 1 and 100.
         MsgBox MyValue

      </script>
   </body>
</html>

上記のスクリプトをHTMLとして保存し、IEでスクリプトを実行すると、次の出力が表示されます。

42

Vbscript-questions-answers