VBAとVBScriptのConstは微妙に異なる
VBAではConstで宣言した定数は次の定数の宣言時には定数として使える。しかしVBSCriptではそれができない。
現象
1.VBAの場合次のコードは成功する
Option Explicit
Const cnsA = "T"
Const cnsB = cnsA & "-"
Const cnsC = cnsB & "shirt"
Sub test()
Debug.Print cnsC
End Sub
2.VBSの場合次のコードは失敗する
Expected literal contant
Const cnsA = "T"
Const cnsB = cnsA & "-"
Const cnsC = cnsB & "shirts"
WScript.Echo cnsC
原因
VBAのConstは定数を使って定義できる
expression 必須。 リテラル値、その他の定数、または、すべての算術演算子や論理演算子 (Is を除く) の任意の組み合わせを指定します。
VBScript の場合は別の定数に依存する定数が作成できない。
エラー原因:
Const で変数を"定数"として定義しましたが、変数が定数でありません。以下の例ではaは変数bに依存するため定数ではありません。
【スクリプト】
b=1
Const a = 1+b
この例からすると cnsBはConstで宣言した定数(cnsA)に依存することになり、エラーになると考えられる。
Expected literal contant
https://www.vbsedit.com/html/0be9852c-97bf-44a9-9980-7a597225b2f8.asp
You declared a constant, but assigned it a variable expression (a value that can change). Constants cannot contain runtime code.
### 公式が紛らわしい
#### VBAと変わらない書き方のようだが、このあとの注(Remark)がある。
expression
Required. Literal or other constant, or any combination that includes all arithmetic or logical operators except Is.
***You can't use variables, user-defined functions, or intrinsic VBScript functions (such as Chr) in constant declarations. By definition, they can't be constants. You also can't create a constant from any expression that involves an operator, that is, only simple constants are allowed.*** Constants declared in a Sub or Function procedure are local to that procedure. A constant declared outside a procedure is defined throughout the script in which it is declared. You can use constants anywhere you can use an expression. The following code illustrates the use of the Const statement:
定数宣言では、変数、ユーザー定義関数、または組み込みのVBScript関数(Chrなど)を使用できません。定義により、定数にすることはできません。また、演算子を含む式から定数を作成することはできません。つまり、単純な定数のみが許可されます。
`Const cnsB = cnsA & "-"`は演算子を含むのと、By definition, they can't be constants. つまり定数を定義(definition)しているため、エラーになるようだ。