Visual Basic におけるステートメントStatements in Visual Basic
Visual Basic におけるステートメントは完全な命令です。A statement in Visual Basic is a complete instruction. キーワード、演算子、変数、定数、および式を含めることができます。It can contain keywords, operators, variables, constants, and expressions. 各ステートメントは、次のいずれかのカテゴリに属します。Each statement belongs to one of the following categories:
宣言ステートメント。変数、定数、またはプロシージャの名前を指定します。データ型を指定することもできます。Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.
実行可能なステートメント。アクションを開始します。Executable Statements, which initiate actions. これらのステートメントでは、メソッドまたは関数を呼び出すことができ、コードのブロックをループまたは分岐できます。These statements can call a method or function, and they can loop or branch through blocks of code. 実行可能なステートメントには、変数または定数に値または式を代入する、代入ステートメント が含まれます。Executable statements include Assignment Statements, which assign a value or expression to a variable or constant.
このトピックでは、各カテゴリについて説明します。This topic describes each category. また、このトピックでは、複数のステートメントを 1 行に結合する方法と、複数の行にわたってステートメントを続ける方法について説明します。Also, this topic describes how to combine multiple statements on a single line and how to continue a statement over multiple lines.
宣言ステートメントDeclaration statements
宣言ステートメントを使用して、プロシージャ、変数、プロパティ、配列、および定数の名前を指定して定義します。You use declaration statements to name and define procedures, variables, properties, arrays, and constants. プログラミング要素を宣言するときに、そのデータ型、アクセス レベル、およびスコープを定義することもできます。When you declare a programming element, you can also define its data type, access level, and scope. 詳細については、「宣言された要素の特性」を参照してください。For more information, see Declared Element Characteristics.
次の例には 3 つの宣言が含まれています。The following example contains three declarations.
Public Sub ApplyFormat()
Const limit As Integer = 33
Dim thisWidget As New widget
' Insert code to implement the procedure.
End Sub
最初の宣言は、Sub
ステートメントです。The first declaration is the Sub
statement. それに対応する End Sub
ステートメントと共に、applyFormat
という名前のプロシージャを宣言します。Together with its matching End Sub
statement, it declares a procedure named applyFormat
. また、applyFormat
が Public
であることを示します。これは、それを参照できるすべてのコードでそれを呼び出せることを意味します。It also specifies that applyFormat
is Public
, which means that any code that can refer to it can call it.
2 番目の宣言は Const
ステートメントであり、Integer
データ型と 33 の値を指定して、定数 limit
を宣言します。The second declaration is the Const
statement, which declares the constant limit
, specifying the Integer
data type and a value of 33.
3 番目の宣言は、変数 thisWidget
を宣言する、Dim
ステートメントです。The third declaration is the Dim
statement, which declares the variable thisWidget
. データ型は特定のオブジェクト、つまり、Widget
クラスから作成されるオブジェクトです。The data type is a specific object, namely an object created from the Widget
class. 任意の基本データ型、または使用しているアプリケーションで公開される任意のオブジェクト型の変数を宣言できます。You can declare a variable to be of any elementary data type or of any object type that is exposed in the application you are using.
初期値Initial Values
宣言ステートメントを含むコードが実行されると、Visual Basic で、宣言された要素に必要なメモリが予約されます。When the code containing a declaration statement runs, Visual Basic reserves the memory required for the declared element. 要素に値が保持されている場合、Visual Basic によって、そのデータ型の既定値に初期化されます。If the element holds a value, Visual Basic initializes it to the default value for its data type. 詳細については、「Dim ステートメント」の "動作" に関する記述を参照してください。For more information, see "Behavior" in Dim Statement.
次の例に示すように、変数には、その宣言の一部として初期値を代入することができます。You can assign an initial value to a variable as part of its declaration, as the following example illustrates.
Dim m As Integer = 45
' The preceding declaration creates m and assigns the value 45 to it.
変数がオブジェクト変数である場合は、次の例に示すように、New 演算子キーワードを使用して宣言するときに、そのクラスのインスタンスを明示的に作成できます。If a variable is an object variable, you can explicitly create an instance of its class when you declare it by using the New Operator keyword, as the following example illustrates.
Dim f As New System.Windows.Forms.Form()
宣言ステートメントで指定する初期値は、実行がその宣言ステートメントに到達するまで変数に代入されないことに注意してください。Note that the initial value you specify in a declaration statement is not assigned to a variable until execution reaches its declaration statement. それまでは、変数にそのデータ型の既定値が含まれます。Until that time, the variable contains the default value for its data type.
実行可能なステートメントExecutable statements
実行可能なステートメントでアクションが実行されます。An executable statement performs an action. プロシージャを呼び出したり、コード内の別の場所に分岐したり、複数のステートメントをループしたり、式を評価したりすることができます。It can call a procedure, branch to another place in the code, loop through several statements, or evaluate an expression. 代入ステートメントは、実行可能なステートメントの特殊なケースです。An assignment statement is a special case of an executable statement.
次の例では、If...Then...Else
制御構造を使用して、変数の値に基づいてさまざまなコード ブロックを実行します。The following example uses an If...Then...Else
control structure to run different blocks of code based on the value of a variable. 各コード ブロック内では、For...Next
ループが指定された回数だけ実行されます。Within each block of code, a For...Next
loop runs a specified number of times.
Public Sub StartWidget(ByVal aWidget As widget,
ByVal clockwise As Boolean, ByVal revolutions As Integer)
Dim counter As Integer
If clockwise = True Then
For counter = 1 To revolutions
aWidget.SpinClockwise()
Next counter
Else
For counter = 1 To revolutions
aWidget.SpinCounterClockwise()
Next counter
End If
End Sub
前の例の If
ステートメントでは、パラメーター clockwise
の値を確認します。The If
statement in the preceding example checks the value of the parameter clockwise
. 値が True
である場合は、aWidget
の spinClockwise
メソッドを呼び出します。If the value is True
, it calls the spinClockwise
method of aWidget
. 値が False
である場合は、aWidget
の spinCounterClockwise
メソッドを呼び出します。If the value is False
, it calls the spinCounterClockwise
method of aWidget
. If...Then...Else
制御構造は、End If
で終わります。The If...Then...Else
control structure ends with End If
.
各ブロック内の For...Next
ループでは、revolutions
パラメーターの値と等しい回数だけ、適切なメソッドを呼び出します。The For...Next
loop within each block calls the appropriate method a number of times equal to the value of the revolutions
parameter.
代入ステートメントAssignment statements
代入ステートメントでは、次の例のように、代入演算子 (=
) の右辺の値を取り、左側の要素に格納することで構成される代入演算を実行します。Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment operator (=
) and storing it in the element on the left, as in the following example.
v = 42
前の例の代入ステートメントでは、リテラル値 42 が変数 v
に格納されます。In the preceding example, the assignment statement stores the literal value 42 in the variable v
.
対象となるプログラミング要素Eligible programming elements
代入演算子の左辺のプログラミング要素では、値を受け入れて格納できる必要があります。The programming element on the left side of the assignment operator must be able to accept and store a value. これは、ReadOnly ではない変数またはプロパティである必要があるか、あるいは配列要素である必要があることを意味します。This means it must be a variable or property that is not ReadOnly, or it must be an array element. 代入ステートメントのコンテキストでは、このような要素は、"左辺値" の場合、lvalue と呼ばれることもあります。In the context of an assignment statement, such an element is sometimes called an lvalue, for "left value."
代入演算子の右辺の値は、式によって生成されます。これは、リテラル、定数、変数、プロパティ、配列要素、その他の式、または関数呼び出しの任意の組み合わせで構成できます。The value on the right side of the assignment operator is generated by an expression, which can consist of any combination of literals, constants, variables, properties, array elements, other expressions, or function calls. 次に例を示します。The following example illustrates this.
x = y + z + FindResult(3)
前の例では、変数 y
に保持されている値を、変数 z
に保持されている値に追加してから、関数 findResult
への呼び出しによって返される値を追加します。The preceding example adds the value held in variable y
to the value held in variable z
, and then adds the value returned by the call to function findResult
. その後、この式の合計値は、変数 x
に格納されます。The total value of this expression is then stored in variable x
.
代入ステートメントのデータ型Data types in assignment statements
次の例に示すように、代入演算子では、数値に加え、String
値も代入することができます。In addition to numeric values, the assignment operator can also assign String
values, as the following example illustrates.
Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.
次の例に示すように、Boolean
リテラルまたは Boolean
式を使用して、Boolean
値を代入することもできます。You can also assign Boolean
values, using either a Boolean
literal or a Boolean
expression, as the following example illustrates.
Dim r, s, t As Boolean
r = True
s = 45 > 1003
t = 45 > 1003 Or 45 > 17
' The preceding statements assign False to s and True to t.
同様に、Char
、Date
、または Object
データ型のプログラミング要素に適切な値を代入することができます。Similarly, you can assign appropriate values to programming elements of the Char
, Date
, or Object
data type. また、インスタンスの作成元のクラスとして宣言された要素に、オブジェクト インスタンスを代入することができます。You can also assign an object instance to an element declared to be of the class from which that instance is created.
複合代入ステートメントCompound assignment statements
"複合代入ステートメント" では、最初に式で演算を行ってから、プログラミング要素に代入します。Compound assignment statements first perform an operation on an expression before assigning it to a programming element. 次の例では、演算子の左辺の変数値を、右側の式の値でインクリメントする、これらの +=
の演算子を示します。The following example illustrates one of these operators, +=
, which increments the value of the variable on the left side of the operator by the value of the expression on the right.
n += 1
前の例では、n
の値に 1 を加算してから、その新しい値を n
に格納します。The preceding example adds 1 to the value of n
, and then stores that new value in n
. これは、次のステートメントに相当する短縮形です。It is a shorthand equivalent of the following statement:
n = n + 1
この型の演算子を使用することで、さまざまな複合代入演算を実行できます。A variety of compound assignment operations can be performed using operators of this type. これらの演算子の一覧と詳細については、「代入演算子」を参照してください。For a list of these operators and more information about them, see Assignment Operators.
連結代入演算子 (&=
) は、次の例に示すように、既存の文字列の末尾に文字列を追加する場合に便利です。The concatenation assignment operator (&=
) is useful for adding a string to the end of already existing strings, as the following example illustrates.
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".
代入ステートメントでの型変換Type Conversions in Assignment Statements
変数、プロパティ、または配列要素に代入する値は、そのターゲット要素に適したデータ型である必要があります。The value you assign to a variable, property, or array element must be of a data type appropriate to that destination element. 一般には、ターゲット要素と同じデータ型の値の生成を試みることをお勧めします。In general, you should try to generate a value of the same data type as that of the destination element. しかし、代入時に他の型に変換できる型もあります。However, some types can be converted to other types during assignment.
データ型間の変換については、「Visual Basic における型変換」を参照してください。For information on converting between data types, see Type Conversions in Visual Basic. 簡単に言えば、Visual Basic では、指定された型の値を、拡大変換される他の型に自動的に変換します。In brief, Visual Basic automatically converts a value of a given type to any other type to which it widens. "拡大変換" は、実行時に常に成功し、データが失われないものです。A widening conversion is one in that always succeeds at run time and does not lose any data. たとえば、Visual Basic では、必要に応じて、Integer
値を Double
に変換します。これは、Integer
が Double
に拡大変換されるためです。For example, Visual Basic converts an Integer
value to Double
when appropriate, because Integer
widens to Double
. 詳細については、「 Widening and Narrowing Conversions」を参照してください。For more information, see Widening and Narrowing Conversions.
縮小変換 (拡大しないもの) は、実行時の失敗、あるいはデータ損失のリスクを伴います。Narrowing conversions (those that are not widening) carry a risk of failure at run time, or of data loss. 型変換関数を使用して、縮小変換を明示的に実行することも、Option Strict Off
を設定して、暗黙的にすべての変換を実行するようにコンパイラに指示することもできます。You can perform a narrowing conversion explicitly by using a type conversion function, or you can direct the compiler to perform all conversions implicitly by setting Option Strict Off
. 詳細については、「暗黙の型変換と明示的な型変換」を参照してください。For more information, see Implicit and Explicit Conversions.
1 行に複数のステートメントを配置するPutting multiple statements on one line
1 行に複数のステートメントを配置し、コロン (:
) 文字で区切ることができます。You can have multiple statements on a single line separated by the colon (:
) character. 次に例を示します。The following example illustrates this.
Dim sampleString As String = "Hello World" : MsgBox(sampleString)
この形式の構文は、便利な場合もありますが、コードを読んだり、保持することが難しくなります。Though occasionally convenient, this form of syntax makes your code hard to read and maintain. したがって、1 つのステートメントを 1 行に収めることをお勧めします。Thus, it is recommended that you keep one statement to a line.
複数行にわたってステートメントを続けるContinuing a statement over multiple lines
ステートメントは通常、1 行に収まりますが、長すぎる場合は、行連結シーケンスを使用して、次の行に続けることができます。これは、スペース、その後に続くアンダースコア文字 (_
)、さらにその後に続く復帰で構成されます。A statement usually fits on one line, but when it is too long, you can continue it onto the next line using a line-continuation sequence, which consists of a space followed by an underscore character (_
) followed by a carriage return. 次の例では、MsgBox
の実行可能なステートメントは 2 行にわたって続きます。In the following example, the MsgBox
executable statement is continued over two lines.
Public Sub DemoBox()
Dim nameVar As String
nameVar = "John"
MsgBox("Hello " & nameVar _
& ". How are you?")
End Sub
暗黙的な行連結Implicit line continuation
多くの場合、アンダースコア文字 (_
) を使用せずに、次の連続する行にステートメントを続けることができます。In many cases, you can continue a statement on the next consecutive line without using the underscore character (_
). 以下の構文要素では、暗黙的にステートメントを次のコード行に続けます。The following syntax elements implicitly continue the statement on the next line of code.
コンマ (
,
) の後。After a comma (,
). 次に例を示します。For example:Public Function GetUsername(ByVal username As String, ByVal delimiter As Char, ByVal position As Integer) As String Return username.Split(delimiter)(position) End Function
開きかっこ (
(
) の後、または閉じかっこ ()
) の前。After an open parenthesis ((
) or before a closing parenthesis ()
). 次に例を示します。For example:Dim username = GetUsername( Security.Principal.WindowsIdentity.GetCurrent().Name, CChar("\"), 1 )
左中かっこ (
{
) の後、または右中かっこ (}
) の前。After an open curly brace ({
) or before a closing curly brace (}
). 次に例を示します。For example:Dim customer = New Customer With { .Name = "Terry Adams", .Company = "Adventure Works", .Email = "terry@www.adventure-works.com" }
詳細については、「オブジェクト初期化子: 名前付きの型と匿名型」または「コレクション初期化子」を参照してください。For more information, see Object Initializers: Named and Anonymous Types or Collection Initializers.
XML リテラル内の開始埋め込み式 (
<%=
) の後、または埋め込み式の終了 (%>
) の前。After an open embedded expression (<%=
) or before the close of an embedded expression (%>
) within an XML literal. 次に例を示します。For example:Dim customerXml = <Customer> <Name> <%= customer.Name %> </Name> <Email> <%= customer.Email %> </Email> </Customer>
詳細については、「XML での埋め込み式」を参照してください。For more information, see Embedded Expressions in XML.
連結演算子 (
&
) の後。After the concatenation operator (&
). 次に例を示します。For example:cmd.CommandText = "SELECT * FROM Titles JOIN Publishers " & "ON Publishers.PubId = Titles.PubID " & "WHERE Publishers.State = 'CA'"
詳細については、「機能別の演算子一覧」を参照してください。For more information, see Operators Listed by Functionality.
代入演算子 (
=
、&=
、:=
、+=
、-=
、*=
、/=
、\=
、^=
、<<=
、>>=
) の後。After assignment operators (=
,&=
,:=
,+=
,-=
,*=
,/=
,\=
,^=
,<<=
,>>=
). 次に例を示します。For example:Dim fileStream = My.Computer.FileSystem. OpenTextFileReader(filePath)
詳細については、「機能別の演算子一覧」を参照してください。For more information, see Operators Listed by Functionality.
式内の 2 項演算子 (
+
、-
、/
、*
、Mod
、<>
、<
、>
、<=
、>=
、^
、>>
、<<
、And
、AndAlso
、Or
、OrElse
、Like
、Xor
) の後。After binary operators (+
,-
,/
,*
,Mod
,<>
,<
,>
,<=
,>=
,^
,>>
,<<
,And
,AndAlso
,Or
,OrElse
,Like
,Xor
) within an expression. 次に例を示します。For example:Dim memoryInUse = My.Computer.Info.TotalPhysicalMemory + My.Computer.Info.TotalVirtualMemory - My.Computer.Info.AvailablePhysicalMemory - My.Computer.Info.AvailableVirtualMemory
詳細については、「機能別の演算子一覧」を参照してください。For more information, see Operators Listed by Functionality.
Is
およびIsNot
演算子の後。After theIs
andIsNot
operators. 次に例を示します。For example:If TypeOf inStream Is IO.FileStream AndAlso inStream IsNot Nothing Then ReadFile(inStream) End If
詳細については、「機能別の演算子一覧」を参照してください。For more information, see Operators Listed by Functionality.
メンバー修飾子文字 (
.
) の後、およびメンバー名の前。After a member qualifier character (.
) and before the member name. 次に例を示します。For example:Dim fileStream = My.Computer.FileSystem. OpenTextFileReader(filePath)
しかし、
With
ステートメントを使用する場合、または型の初期化一覧に値を指定する場合は、メンバー修飾子文字の後に行連結文字 (_
) を含める必要があります。However, you must include a line-continuation character (_
) following a member qualifier character when you are using theWith
statement or supplying values in the initialization list for a type.With
ステートメントまたはオブジェクト初期化一覧を使用する場合は、代入演算子 (=
など) の後で改行することを検討してください。Consider breaking the line after the assignment operator (for example,=
) when you are usingWith
statements or object initialization lists. 次に例を示します。For example:' Not allowed: ' Dim aType = New With { . ' PropertyName = "Value" ' Allowed: Dim aType = New With {.PropertyName = "Value"} Dim log As New EventLog() ' Not allowed: ' With log ' . ' Source = "Application" ' End With ' Allowed: With log .Source = "Application" End With
詳細については、「With...End With ステートメント」または「オブジェクト初期化子: 名前付きの型と匿名型」を参照してください。For more information, see With...End With Statement or Object Initializers: Named and Anonymous Types.
XML 軸プロパティの修飾子 (
.
、.@
または...
) の後。After an XML axis property qualifier (.
or.@
or...
). しかし、With
キーワードを使用する場合は、メンバー修飾子を指定するときに行連結文字 (_
) を含める必要があります。However, you must include a line-continuation character (_
) when you specify a member qualifier when you are using theWith
keyword. 次に例を示します。For example:Dim customerName = customerXml. <Name>.Value Dim customerEmail = customerXml... <Email>.Value
詳細については、「XML 軸プロパティ」を参照してください。For more information, see XML Axis Properties.
属性を指定する場合は、小なり記号 (<) の後、または大なり記号 (
>
) の前。After a less-than sign (<) or before a greater-than sign (>
) when you specify an attribute. また、属性を指定する場合は、大なり記号 (>
) の後。Also after a greater-than sign (>
) when you specify an attribute. しかし、アセンブリ レベルまたはモジュール レベルの属性を指定する場合は、行連結文字 (_
) を含める必要があります。However, you must include a line-continuation character (_
) when you specify assembly-level or module-level attributes. 次に例を示します。For example:< Serializable() > Public Class Customer Public Property Name As String Public Property Company As String Public Property Email As String End Class
詳細については、「属性の概要」を参照してください。For more information, see Attributes overview.
クエリ演算子 (
Aggregate
、Distinct
、From
、Group By
、Group Join
、Join
、Let
、Order By
、Select
、Skip
、Skip While
、Take
、Take While
、Where
、In
、Into
、On
、Ascending
、およびDescending
) の前か後。Before and after query operators (Aggregate
,Distinct
,From
,Group By
,Group Join
,Join
,Let
,Order By
,Select
,Skip
,Skip While
,Take
,Take While
,Where
,In
,Into
,On
,Ascending
, andDescending
). 複数のキーワードで構成されているクエリ演算子 (Order By
、Group Join
、Take While
、およびSkip While
) のキーワードの間で改行することはできません。You cannot break a line between the keywords of query operators that are made up of multiple keywords (Order By
,Group Join
,Take While
, andSkip While
). 次に例を示します。For example:Dim vsProcesses = From proc In Process.GetProcesses Where proc.MainWindowTitle.Contains("Visual Studio") Select proc.ProcessName, proc.Id, proc.MainWindowTitle
For Each
ステートメント内のIn
キーワードの後。After theIn
keyword in aFor Each
statement. 次に例を示します。For example:For Each p In vsProcesses Console.WriteLine("{0}" & vbTab & "{1}" & vbTab & "{2}", p.ProcessName, p.Id, p.MainWindowTitle) Next
詳細については、For Each...Next ステートメント を参照してください。For more information, see For Each...Next Statement.
コレクション初期化子内の
From
キーワードの後。After theFrom
keyword in a collection initializer. 次に例を示します。For example:Dim days = New List(Of String) From { "Mo", "Tu", "We", "Th", "F", "Sa", "Su" }
詳細については、「コレクション初期化子」を参照してください。For more information, see Collection Initializers.
コメントの追加Adding comments
ソース コードは、それを記述したプログラマであっても、見ればすぐわかるとは限りません。Source code is not always self-explanatory, even to the programmer who wrote it. そのため、コードの文書化に役立つように、ほとんどのプログラマは埋め込みコメントを十分に利用します。To help document their code, therefore, most programmers make liberal use of embedded comments. コード内のコメントでは、後でそれを読んだり、操作を行うすべてのユーザーに対して、プロシージャまたは特定の命令について説明することができます。Comments in code can explain a procedure or a particular instruction to anyone reading or working with it later. Visual Basic では、コンパイル時にコメントが無視され、コンパイルされたコードには影響しません。Visual Basic ignores comments during compilation, and they do not affect the compiled code.
コメント行はアポストロフィ ('
) または REM
で始まり、その後にスペースが続きます。Comment lines begin with an apostrophe ('
) or REM
followed by a space. 文字列内の場合を除き、コード内の任意の場所に追加することができます。They can be added anywhere in code, except within a string. ステートメントにコメントを追加するには、ステートメントの後にアポストロフィまたは REM
を挿入し、その後にコメントを続けます。To append a comment to a statement, insert an apostrophe or REM
after the statement, followed by the comment. コメントを独自の行に続けることもできます。Comments can also go on their own separate line. これらの考えられる例を以下に示します。The following example demonstrates these possibilities.
' This is a comment on a separate code line.
REM This is another comment on a separate code line.
x += a(i) * b(i) ' Add this amount to total.
MsgBox(statusMessage) REM Inform operator of status.
コンパイル エラーの確認Checking compilation errors
コード行を入力した後、その行の下に青い破線が表示されている場合 (エラー メッセージも表示される場合があります)、ステートメントに構文エラーがあります。If, after you type a line of code, the line is displayed with a wavy blue underline (an error message may appear as well), there is a syntax error in the statement. ステートメントの問題を確認し (タスク一覧を調べるか、マウス ポインターでエラーをポイントしてエラー メッセージを読んで)、修正する必要があります。You must find out what is wrong with the statement (by looking in the task list, or hovering over the error with the mouse pointer and reading the error message) and correct it. コード内の構文エラーをすべて修正するまで、プログラムでは正しくコンパイルできません。Until you have fixed all syntax errors in your code, your program will fail to compile correctly.
関連項目Related sections
用語Term | 定義Definition |
---|---|
代入演算子Assignment Operators | = 、*= 、&= などの代入演算子に関する言語リファレンス ページへのリンクを提供します。Provides links to language reference pages covering assignment operators such as = , *= , and &= . |
演算子および式Operators and Expressions | 要素を演算子と組み合わせて新しい値を生成する方法を示します。Shows how to combine elements with operators to yield new values. |
方法: コード内でステートメントを分割および連結するHow to: Break and Combine Statements in Code | 1 つのステートメントを複数の行に分割する方法と、複数のステートメントを同じ行に配置する方法を示します。Shows how to break a single statement into multiple lines and how to place multiple statements on the same line. |
方法: ステートメントへのラベル付けHow to: Label Statements | コード行にラベルを付ける方法を示します。Shows how to label a line of code. |