VBS tutorial (entry level)

Very good VBS tutorial (with examples)

Recommended first article:

Let’s talk about VBScript. It is mainly for novices. Friends who know programming should not waste time. If you want to get started with the following VBScript, you can also do it. But since you have the basics of programming, it is recommended to go directly to some reference books to read. It will be faster.

What is VBScript? The full name of VBScript is: Microsoft Visual Basic Script Editon. (Microsoft visual BASIC script version). As its name suggests, VBS (further abbreviation for VBScript) is a scripting language based on Visual Basic. Let me explain further, Microsoft Visual Basic is a set of visual programming tools produced by Microsoft. The syntax is based on the Basic script language, which means it is not compiled into a binary file. The source code is interpreted and executed directly by the host. To put it simply, you The program you write does not need to be compiled into .exe. Instead, the .vbs source program is directly sent to the user, and the user can execute it.

I know that what rookies are most concerned about now is what tool to use to develop VBS programs. The answer is: Notepad. I am not kidding. In fact, any text editor can be used to develop VBS programs, but Notepad is It comes with the system and is easier to find. Nonetheless, I still recommend that you download a professional text editor, because these tools can provide functions such as "syntax highlighting", which is more convenient for development. Which one you use is up to you. , I prefer Edit Plus (2.10).

  OK, let's first write a VBScript program to warm up.

REM Enter and echo your name

'Use InputBox and Msgbox functions

Dim name,msg

msg="Please enter your name:"

name=Inputbox(msg,"name")

Msgbox(name)

  Enter the above program list into Notepad, and then save it as a file with a .vbs extension (select "All files" in "Save as type"). Then double-click to run and observe the running results. Note: Please enter the program list yourself , don't copy->paste!

Let me explain this program. The first and second lines start with the "REM" statement and " ' " respectively. These two things have the same function, indicating that this line is a comment line, that is, what are these two lines? Not dry, just used to explain the function of this program, copyright information, etc. The comment line is one of the most important parts of the program. Although it is not necessary, it is useful for other people to read the source code and analyze the source code themselves. Very beneficial. Good practice is to add clear, concise comments where necessary.

  Dim is used to declare a variable. In VBS, the variable type is not that important. That is to say, VBS will automatically identify the variable type for you, and the variable does not have to be declared before use. The program will dynamically allocate variable space. In VBS You don't need to consider whether the name stores an integer or a decimal (scientific name is "floating point number"), or whether it is a string (a string of characters, such as: "Hello World"), VBS will automatically handle it for you. So the first The three lines of statements can be deleted and the effect will not change, but I strongly object to this. The basic principle of a variable is: declare it first, then use it. The variable name starts with a letter, and you can use underscores and numbers, but you cannot use those already defined by VBS. Words, such as dim, cannot be pure numbers.

  The next line is called "assignment", "=" is the assignment symbol, not the equal sign in mathematics, although it looks the same. This is the orthodox understanding, and there is nothing wrong with it if you understand it as equal. The left side of the assignment symbol is a variable, and the right side is the value to be assigned to the variable. After the assignment, the variable msg is equivalent to the string "Please enter your name:" in the program, but when msg is copied again, the original value will be Disappear. Not only strings, but also any other variables are assigned in this way, for example: a=2, b=12.222, etc.

  Further down, Inputbox and Msgbox are built-in functions of VBS. A function is equivalent to a "black box" with input (parameters) and output (return value). You don't need to understand how the function works, as long as you understand the function. Just do whatever it can, we can also define our own functions, but that will be discussed later. Now we only need to understand that a function can have a return value or not, and can have parameters or not. For example, Inputbox has a return value function, we use the variable on the left side of the assignment number to "catch" the return value of the InputBox - which is the content you entered. In the brackets on the right side of the inputbox is the parameter list, each parameter is separated by ",", each parameter It has different functions. For example, the first parameter will be displayed in the prompt. We pass the msg variable as the first parameter to the Inputbox function, and msg="Please enter your name:", so we You will see "Please enter your name:" in the prompt bar. The second parameter is the title of the dialog box. We use a direct quantity (scientific name is "constant", here it is "string constant") to pass it to the function. Of course, you can also You can pass variables. Inputbox also has many parameters. For example, you add a "," after "name" and then enter a string of characters (a string, a string of characters wrapped in double quotes "" is called a string) and then run , look at the results. You will find that the text box used for input has a default value. This is the role of the third parameter.

The Msgbox function is a function used for output. There is no special output function in VBS (print in BASIC, printf in C), so we can only use a dialog box to observe the output results. There is only one necessary parameter for Msgbox, which is The output content, in this case, we don't need to pay attention to the return value of msgbox. We will discuss Msgbox and Inputbox in the future, today is just a warm-up, that's it.

Key points:

1) Comments (starting with REM or ') lines have no effect in the program, but they make it easier for others to read your program.

2) 变量好像一个盒子,或一个代号,可以代表你想代表的东西. 变量赋值使用"="

3) 以""包裹起来的字符称之为"字符串"

4) 函数像一个"黑箱",有参数和返回值,用"="左边的变量可以接住返回值

5) Inputbox函数弹出一个输入对话框,Msgbox则用于输出

作业:

1) 试验Inputbox的第三个参数

2) 写一段程序输出你的年龄

3) 写一段程序进行3次输入,分别输入你和你父母的姓名(要求显示提示),并分3次输出。

--------------------------------------------------------------------------------

第二篇:

我真没想到,第一次的作业竟然有人不会。

  看来要讲的非常非常细致才行,嗯,今天讲各种“量”和基本运算。

先说常量,这个比较简单。

  什么是常量呢,常量就是其值不可变化的量。

  常量分为两种:第一种,自然常量。这叫是因为它们本身就是常量,你怎么更改21的值呢? 他永远都是21,不可能变成46。

如果你在程序中使用"21=46",这样的语句将会引发一个错误。同样的,字符串也是常量(还记得字符串吗? 就是包裹在""之间的一串字符),"Hello World"就是一个例子,如果你使用"Hello World"="Bye"这样的语句同样会引发一个错误。你能举出自然常量的更多例子吗?

  第二种,是我们自己定义的常量,这种量也使用代号,他们也被赋值,但和变量的不同点在于,他们在定义的时候被赋值,以后就不能改变了,如果企图改变将会引发一个错误。定义一个变量,我们使用"const"这个关键字(关键字的意思是系统定义了有特殊功能的字,不能作为变量名或常量名使用),格式是:const 常量名=常量值

例如:

const PI=3.1415926

const NAME="记忆碎片"

  这样我们就定义了两个常量,PI和NAME,一般说来,常量名全部使用大写,但也可以不用,随你喜好。将一些在程序中不需要改变的值定义为常量是个好习惯,这样能防止不必要的意外。另外,使用自定义常量也可以减少你的工作量。 比如:

msgbox("Hello World")

msgbox("Hello World")

msgbox("Hello World")

msgbox("Hello World")

msgbox("Hello World")

  这个程序输出五次Hello World,如果你想要改变输出为Bye-Bye,就必须修改全部程序,当然你可以手动修改5次,但如果你要输出1000次呢?常量就可以替我们解决这个问题:

const hw="Hello World"

msgbox(hw)

msgbox(hw)

msgbox(hw)

msgbox(hw)

msgbox(hw)

  这样当你要修改输出的时候只要修改hw的值就行了。

  好了,现在我们来看看编程的第一块重要“基石”:变量。解释变量最好的办法我觉得是“盒子”,一个变量好像一个盒子,里面只能装一个东西,当你要装进去别的东西的时候必须把原有的东西拿出来。这个“盒子”是有名称的,当你在程序中使用变量的时候,系统会打开盒子取出里面的东西,让这些东西参与处理,而不是盒子。有些语言是很依赖“盒子”里面装些什么东西,这样才能找到合适的“盒子”(比如C语言),但VBS给我提供的是能够自动伸缩的“魔术盒”,我们不用关心装进去的是什么东西,VBS会自动调整盒子的大小。例如:

Dim a1,a2,a3

a1=14

a2=12.23

a3="Hello"

而不用像C语言那样麻烦,或者是VB的正规声明(VB可以声明也可以不用)那样:

int a1; Dim a1 as integer

float a2; Dim a2 as Double

char* a3; Dim a3 as strnig

a1=14; a1=14

a2=12.23; a2=12.23

a3="Hello"; a3="Hello"

嗯……扯远了……

  What are variables used for? Wow, that's quite useful. The simplest is that you cannot determine the value of the variable when the program is running. For example, in the program we compiled in the previous lesson to enter names, you cannot be sure what the InputBox returns (remember the return value of the Inputbox? It is what you input) , so you have no way to deal with various situations, but we use the "box" name to store the user's name. When we use it, we only need to know the name of the box name. The system will open it by itself and put the contents inside. Use the content. For another example, we write a program to calculate the area of ​​a rectangle. For example, this program is to be distributed to primary school students:

dim a,b,s

a=15

b=12

s=a*b

msgbox(s)

  In this way, we can find the area of ​​a rectangle with a length of 15 and a width of 12. Isn't it very simple? Of course, this program can also be written like this:

dim s

s=15*12

msgbox(s)

  This seems to make the program much shorter and saves memory, but it is not an encouraged approach. Why? please look below.

  Now, our program needs to become something decent. Whose program needs someone else to modify the source code before it can be used?

  So, we have to accept input from the user, remember? InputBox function.

  The modified procedure is as follows:

dim a,b,s

a=inputbox("请输入矩形的长:")

b=inputbox("请输入矩形的宽:")

s=a*b

msgbox(s)

  OK, with this modification, we can calculate the area of ​​the rectangle no matter what data the user inputs. Can you change it if you use s=15*12? Of course not.

  I think you have discovered that mathematical calculations in VBS are no different from real arithmetic. +,-,*,/,(),[],{} are all used in the same way, such as:

dim ans

ans=12+32/4+[(23-10)*2]

msgbox(ans)

  The rules of the four arithmetic operations are also valid in programming. You can regain the fun you had in elementary school in programming (you hate mathematics? Then don’t learn computers).

  An interesting operator in programming is "mod". This operator is called the "remainder operator", which is to obtain the remainder of a division, for example:

dim a

a=16 mod 5

  Do you know what a is equal to? Bingo! Yes, it’s 1. Because 16 / 5 =3...1, the result of mod calculation is 1.

  Another operator is "^" (the small arrow above "6" on the keyboard), which means "exponentiation" (or "square"), for example:

dim a,b,c

a=2

b=a^2

c=a^3

msgbox(a)

msgbox(c)

  则b=a*a=4,c=a*a*a=8

  Let’s not talk too much at one time. We will stop here this time and summarize it now.

Key points:

1) Constants are divided into natural constants and custom constants. The values ​​of constants cannot be modified.

2) Variables are like boxes. We don’t care what is in the box, but we must know the name of the box.

3) There is no difference in the four arithmetic operations in programming

4) MOD is the remainder operation

Operation:

1) Write a program to calculate the area of ​​a circle. The radius is given by the user (using Inputbox). The PI value is 3.14159.

2) Write a program to get the remainder of 20 / 3

I guess everyone is tired of reading this, so let me give you an example of the Westward Journey 2 game calculator.

Xiao Hei set up a stall in front of the gang to sell medicine. He sold a total of 56 supernatural incense today, each with a selling price of 2170. So how much money did he make? (The price of supernatural incense sold in pharmacies is 2160)

In the question, 56 and 2170 are variables. You can think about how to write the code, and then read on.

dim m,n,x,msg

msg="小黑在帮派门口摆摊卖药,今天共卖了 n 个灵异天香,每个的出售价格为 m ,那么他赚了多少钱?"

n=inputbox(msg,"灵异天香个数n","请在此输入灵异天香个数n")

m=inputbox(msg,"每个售价m","请在此输入每个药的出售价格m")

x=(m-2160)*n

msgbox("答案:" & x)

Copy and paste this code into a text file, then change the .txt suffix of the text file to .vbs and double-click to run it to see the effect. If you can't see the .txt suffix, go to My Computer-Control Panel-Folder Options-View-uncheck the "Hide extensions for known file types"-OK.

--------------------------------------------------------------------------------

Article 3:

First, let me solve some questions from the last course.

First, the remainder problem, 16 / 5 = 3...1, is because I changed the previous part but forgot to change the latter part, sorry.

Second, take a look at the program listing:

1)

Dim a,b,c

a=inputbox("a是:","输入半径")

b=Inputbox("b是:","输入半径")

c=a*2+b*2

Msgbox(c)

这个 输入1、2时是6

2)

Dim a,b,c

a=inputbox("a是:","输入半径")

b=Inputbox("b是:","输入半径")

c=(a+b)*2

Msgbox(c)

When you enter 1 and 2, this is 24

  Why is it different? In mathematics, c=(a+b)*2 and c=a*2+b*2 are equivalent, and the same is true in VBS. The problem lies in the "+", in VBS , + not only means a plus sign but also means concatenating two strings, such as "Hello"+"World"="HelloWorld" have you understood? Do you still remember the return value of the InoutBox function? It's a string! This shows the problem. In programming, "1" is not equal to (<>)1. "1" is a character, and 1 is a number, so a and b are both string variables, "1"+" 2"="12", this is just like when we were kidding with our friends and asked them 1+1=?, we always laughed and said "wrong, it should be 11", but why, a can * 2 but no error occurs Woolen cloth? This is a more intelligent performance of VBS. If the content of the string is a number and mathematical operations are performed on it, the string is forced to be converted into a number to participate in the operation. If the string represents a number, but it does not participate in mathematical operations, but If you participate in string operation (merging), it will be treated as a string, so you see a+b=12. At this time, the result of a+b (12) is a string, and it is forced when it is multiplied by 2. Converted to the number 12 so I get the result 24.

  How to modify this program? We need to use another built-in function: int

The function of the int function is to convert the input value into an integer value. We modify it like this:

c=(int(a)+int(b))*2

  This means passing a as a parameter to the int function, the int function will return the integer (your input value), and then let the return value participate in the operation, so as to get the correct answer. Therefore, if you use the inputbox function in the future, it is best to use the int statement to process it: for example, c=int(c) 'c is your own variable.

  Do you think this course is a bit boring? Haha, the variables and operators part is indeed like this, but it would be nice to practice more. This time, we write about something really fun: flow control statements. This part begins with the real programming.

First, the judgment structure is introduced.

  Before that, we first introduce a simple variable type: Boolean. This variable has only two possible values: True, False, that is, true or false. This type of variable is useful in certain situations (such as "switch"). We define a bool variable in the same way as other variables, and assign values ​​in the same way, for example:

dim a,b

a=true

b=false

  Note that true and "true" are different. "true" is a string and true is a Boolean value. They must not be confused.

  Back to the if statement, let's first look at the simplified version of the if statement: if judgment then statement body Let's look at an example:

dim a,b

a=12

b=13

if b>a then msgbox("B is greater than A")

  Let’s just look at the last line. The formula (expression) a>b has a return value, which is of bool type. Because there are only two possibilities for this formula: b is greater than a, and b is not greater than a, so this formula also only has Two possibilities, namely true or false. The if statement determines whether the return value of this expression is true or false. If it is true (true), the statement following then will be executed. If it is false, it will not be executed. You put the value of a Change it to 14 and see if the dialog box still pops up?

  What should we do when we want to execute a multi-line statement after judgment? We need to use a statement block to solve it. Here we can call it a block if

dim a,b

a=12

b=13

if a<b then

msgbox("A小于B")

msgbox("B大于A")

end if

  The two msgbox functions are sandwiched between if and end if. This part is the statement block. Please leave 4-8 (one <Tab> key) spaces before each statement in the block. This is not required, but it is A good habit to see clearly the structure of the program. This way we can run more than one statement. Please pay attention to the three key parts if...then...end if. OK, let me ask a question, Enter a number. If it is less than 100, it will output "error". If it is greater than 100, it will output "correct". I have two program versions here:

dim a

a=inputbox("请输入一个大于100的数")

a=int(a) 'inputbox返回的是字符串, 我们把他变成整数 : )

if a>100 then msgbox("正确")

if a<100 then msgbox("错误")

还有一个更简单的

dim a

a=inputbox("请输入一个大于100的数")

a=int(a) 'inputbox返回的是字符串, 我们把他变成整数

if a>100 then

msgbox("正确")

else

msgbox("错误")

end if

  You see there is an extra else. The function of else is to execute when the expression to be judged is false. In this way, the program can handle two different situations. Don't forget to end with end if

  Hehe, I am a pervert. Now I want you to handle three situations, <100,=100,>100, and write them in an if structure. What should you do? I will give you the answer:

dim a

a=inputbox("请输入一个大于100的数")

a=int(a) 'inputbox返回的是字符串, 我们把他变成整数

if a>100 then

msgbox("正确")

elseif a=100 then

msgbox("老大, 你耍我?")

else

msgbox("错误")

end if

  Enter 100 this time to see what it is? else if statement can appear multiple times in the if structure to flexibly judge different situations (if you want to judge too many, please use the "selection structure", which will be discussed later ), execute the statement in else when all elseifs have been processed and no conditions are met. Another example:

Dim a,b,c,d

a=inputbox("a是:","输入半径")

b=Inputbox("b是:","输入半径")

d=Inputbox("答案:","输入答案")

c=a*2+b*2 '这里没有问题, 会自动转换

if d=c then

Msgbox("你好聪明")

else

Msgbox("你好猪头 自己的题还不会!")

end if

  Look at this again. No matter how correct your answer is, you are still a pig. Haha, I am not fooling you, but the return type of inputbox at the beginning of the article is fooling you. d is the return value of inputbox, which is a string, and c is the result of an integer calculation, it is an integer. A string is not equal to an integer in any way, although they are literally the same: "8" <> (not equal to the sign) 8, so the value of the predicate of if It is always false, and the else part of the statement is always executed. We can modify it like this

Dim a,b,c,d

a=inputbox("a is:","input radius")

b=Inputbox("b is:","Input radius")

d=Inputbox("Answer:","Enter the answer")

d=int(d)

'Here we take out the value of d, turn it into an integer, and put it back into the box "d"

c=a*2+b*2

if d=c then

Msgbox("You are so smart")

else

Msgbox("Hello Zhutou, I still don't know the questions!")

end if

  This is successful. This is also an annoying part of the Inputbox function. There is no other way to do it. There is no other good input method in vbs.

  Speaking of if, we have to talk about logical operators. Today we will introduce two types, "and" and "or". After learning the if statement, I will give you an example and you will understand it at a glance.

dim a,b

a=inputbox("Enter a number>10")

b=inputbox("Enter another number>10")

a=int(a)

b=int(b)

if a>10 and b>10 then

msgbox("correct")

else

msgbox("Error")

end if

  This program allows you to enter two values, both of which must be greater than 10. As long as one of them is not greater, an error will be output.

dim a,b

a=inputbox("Enter a number>10")

b=inputbox("Enter another number>10")

a=int(a)

b=int(b)

if a>10 or b>10 then

msgbox("correct")

else

msgbox("Error")

end if

  This program allows you to enter two values. As long as one of them is greater than 10, it will return success. In fact, and and or are easy to understand. I read the sentence "if a>10 or b>10 then" in Chinese like this: " If a is greater than 10 or b is greater than 10, then...". Isn't this easy to understand?

  OK, let's look at a new structure. Today's class is over. It's already midnight and I'm exhausted.

  When your program has to deal with many different judgment situations, elseif..then will make the program look very messy, so there is a select case structure specifically to deal with this situation. The syntax structure of select case is very simple:

select case variable name

case value

statement

case value

statement

case else

statement

end select

  Let us give an example to explain it simply:

dim a

a=inputbox("Enter a value from 1 to 3")

a=int(a) 'Handle the problem of inputbox returning string

select case a

case 1

msgbox("一")

case 2

msgbox("二")

case 3

msgbox("三")

case else

msgbox("Input error")

end select

  This example converts the three Arabic numerals 1, 2, and 3 into Chinese uppercase numerals. This program is written in the form of if...elseif as follows

dim a

a=inputbox("Please enter a value from 1 to 3")

a=int(a)

if a=1 then

msgbox("一")

elseif a=2 then

msgbox("二")

elseif a=3 then

msgbox("三")

else

msgbox("Input error")

end if

  No matter what, please choose.

  OK, that’s the end of today, let’s summarize:

Key points:

1) The inputbox returns a string, not a number, and must be converted into a number using the form a=int(a)

2) There are only two values ​​of bool variables: true, false

2.5) If the expressions on both sides of and are true, then return true. If one of the expressions on both sides of or is true, then return true

3) Format of if statement

4) Format of select...case

Operation:

1) Use 3 bool values ​​to store whether your 3 siblings are male (hint: sister1male=false)

2) Given a number, if it is greater than 10 and less than 20, it will output "correct", otherwise it will output "error"

3) Enter 12 or 15, the output will be "correct", otherwise the output will be "error"

4) Convert all positive integers within 5 into larger Chinese numbers

5) Design a program by yourself and apply today’s knowledge

--------------------------------------------------------------------------------

Part 4: Loop Structure

  Let’s take a look at a question first: The shopping mall performs daily settlement and is required to add up today’s turnover and enter a number each time. This question is actually very simple, but it is quite troublesome to complete this question based on the knowledge we have learned so far. Let's analyze it. First, we need to know the number of transactions so that we can control the number of inputs. However, this design is very inefficient and the program must be redesigned every day. Assume that 5 transactions were made today. The following is the source program:

dim sum

sum=0 'Initialize variables

sum=sum + int(inputbox("Please enter the transaction amount"))

'sum=sum+x This form takes out its own value, performs an operation, and then puts it back into itself. This method is very useful.' Function nesting is used here, and the return value of the inputbox is directly passed to the int function. , converted into an integer, the same below

sum=sum + int(inputbox("Please enter the transaction amount"))

sum=sum + int(inputbox("Please enter the transaction amount"))

sum=sum + int(inputbox("Please enter the transaction amount"))

sum=sum + int(inputbox("Please enter the transaction amount"))

msgbox(sum)

  Did you see that I designed the program by copying the calculation process 5 times? This kind of program can be used in places with few transactions such as automobile exchanges. If it is placed in a supermarket, it will have to be copied and pasted thousands of times. ? What we are talking about today can overcome this shortcoming. First, let us talk about the following Do...Loop statement.

  The structure of do...loop looks very simple, it is: do...loop, that's it. This structure continuously executes the statements between do and loop (scientific name: loop body),

Never stop. For example:

do

msgbox("This message will appear repeatedly. To stop the program, please use the task manager (Ctrl+Alt+Del) to kill the wscript process")

loop

  Run this program, and when you click and close a dialog box, another one will appear immediately. You can never finish clicking, there is always the next one. Who would run such a program? Unless it is to cause trouble for others (I have done this kind of thing) , so there is another statement in the do..loop structure: exit do. This statement will terminate the loop and jump to the statement after the loop to continue.

Execution. According to an example:

dim a 'Note: constants do not need to be declared in dim, otherwise an error will occur

const pass="123456" 'This is a string, please wrap it with "". Set the password as a constant and cannot be changed

do

a=inputbox("Please enter password")

if a=pass then

msgbox("Password verification successful")

exit do

end if

loop

  This program will keep asking you for your password until you enter the correct password. (If can be nested in another if, or in a loop, so be sure to use indentation to make it clear. various parts of the program). This program is very classic, and early programs did this. But we are Hackers, so

We understand the security of the system. This unlimited authentication program is easily cracked. We need to limit the number of authentications. The modified procedure is as follows

dim a,ctr

ctr=0 'Set counter

const pass="pas123_" 'The above one is a weak password, change it to a stronger one this time

do

if ctr=3 then

msgbox("The authentication limit has been reached, the authentication process is closed")

exit do

else

a=inputbox("Please enter password")

if a=pass then

msgbox("Authentication successful")

msgbox("(You can add a message here after success)")

exit do

else

ctr=ctr+1 'If the password is wrong, increase the error authentication count by one

msgbox("Authentication error, please check password")

end if

end if

loop

  Try running this program. When you get 3 errors, it will stop asking for the password again and close the program. The program used to limit the number of times for telnet authentication is similar to this. What you should pay attention to is the nested if statement. Read it carefully. This program may be difficult to understand, so please try to design a similar program yourself.

  In fact, to add verification function to do...loop, it is not necessary to use if, we can directly use do. Let me introduce the while keyword, while can be placed after do or loop, and then followed by Expression, when the value of the expression is true (the expression is established), the loop body will be run. Let's take a look at the modified

program"

dim a,ctr

ctr=0

const pass="pas123_"

do while ctr<3

a=inputbox("请输入密码")

if a=pass then

msgbox("认证成功")

msgbox("(你可以在这里加一段成功后得到的信息)")

exit do

else

ctr=ctr+1 '如果密码出错就增加一次错误认证计数

msgbox("认证出错, 请检查密码")

end if

loop

dim a,ctr

ctr=0

const pass="pas123_"

do

a=inputbox("请输入密码")

if a=pass then

msgbox("认证成功")

msgbox("(你可以在这里加一段成功后得到的信息)")

exit do

else

ctr=ctr+1 '如果密码出错就增加一次错误认证计数

msgbox("认证出错, 请检查密码")

end if

loop while ctr<3

  The function is the same, why should it be placed after the loop? You will know by changing the value of ctr to 3. The program after while will exit directly after do, and an authentication will be allowed after the loop, and the loop will not end until the end. The opposite of while is until. Its usage is the same as while, but it only executes the loop body when the value of the following expression is false (the expression is not true). Please try it yourself.

  ok, let’s look at another loop structure, for...next. This loop structure is based on counting and is also the most common loop structure in programming.

dim i

for i=0 to 5

msgbox(i)

next

  Did you see it? The output i is incremented each time, but we did not explicitly indicate that i should be incremented. When i reaches 5, the loop ends. Because it starts from 0, the loop body is executed 6 times. This is It's important that most things start at 0 instead of 1. This program can also be written as

The form of do:

dim i

i=0

do while i<5

msgbox(i)

i=i+1 'Because do cannot be counted automatically, it must be added manually

loop

  Anyway, for is easier to use. for is very useful in programming. Let’s give another example and talk about nested loops by the way.

dim i,j

for i=1 to 9

for i=1 to 9

str=str & i * j & " " '& is the symbol for concatenating strings

next 'Each next corresponds to a for

next

  Take a look at the running results. Does it remind you of the math teacher in elementary school (ugly face)? Please note that there is a "big" for and a small for. After the small for completes one cycle, the big for The for is only executed once (in other words, the big for is executed once, and the small for is executed 9 times), so a total of ninety-nine and eighty times are executed.

Once. In the big for, there can be not only a small for, but also other statements. Let's modify the source program:

dim i,j

for i=1 to 9

for i=1 to 9

str=str & i * j & " "

next 'Each next corresponds to a for

str=str & vbCrlf 'vbCrlf is equivalent to the Enter key on the keyboard. Because you cannot enter on the keyboard, the system defines a default constant

next

  After this run is completed, the output results are divided according to the multiplier. After each small for is run, a new line is changed (via vbcrlf).

  The content this time may be difficult for novices to understand. There is only one way to master it: practice more. In addition, I saw many people on the forum still asking: "What tool should I use to compile VBScript?" I was very angry. It has been explained in the article: Just use Notepad to edit the source code, and then save it as a program with a .vbs extension. Please don’t ask again. In addition, a domestic junk software "Super X Tyrant" has taken over the vbs extension, please uninstall that junk.

  Let’s summarize:

Key points:

1) Usage of do..loop and exit do

2) while executes the loop body when the expression is true, and vice versa until

3) for...next is a counting loop, and the counter is incremented each time it is executed.

4) The function and writing method of nested loops

4.5) & is used to connect strings

5) vbCrLf is equivalent to the Enter key on the keyboard

Operation:

1) There is such a question in the Chinese mathematics classic "Nine Chapters on Arithmetic": One hundred dollars buys one hundred chickens, a rooster costs 5 dollars, a hen costs 3 dollars, and two chicks cost 1 dollar (I use this data as a reference It’s from a programming book, but I remember there are 3 males, 1 female, and 1 chicken. No matter, just follow the instructions in the book.) How many ways can you buy these chickens? If you don’t understand. I said it in vernacular: Someone wanted to buy chickens. He bought exactly 100 chickens for 100 yuan. The prices are as follows: Male: 5$, Female: 3$, Small: 1$ for 2. I want you to find out how many chickens to sell in total. Method (How to match male and female babies). Please use loop to solve this problem.

PS: Today's article was written in a hurry, and most of the codes are not experimental. Please check it yourself. Also, I won’t tell you the answer to the last assignment. I don’t know if you like to do this kind of questions, or the simpler ones before?

--------------------------------------------------------------------------------

Article 5:

Today we’ll look at the last topic of the language itself: arrays.

  To understand "array", I think another translation of this concept is easier to learn: "array", yes, an array is an array, an array of data. The simplest example is a database system, assuming you want to store For the English scores of 20 students, if you did not use arrays, you would have to create 20 different variables, which would be exhausting. An array is a group of data (or n groups) of the same type (important!), used to store related quantities. The simplest array is a one-dimensional array, let's learn about it first.

  What is a one-dimensional array? Below 3 dimensions, you can use geometric knowledge to understand the concept of "dimension". One dimension is equivalent to a line, two dimensions is a rectangle, and three dimensions is a cuboid. I know it is very strange to say this. Abstractly, it will be easier to understand if we first take an example of a one-dimensional array.

dim a(9) 'Start from zero

for i=0 to 9

a(i)=i 'Fill each array element

msgbox(a(i)) 'Output array elements

next

  We can see that the method of defining an array is no different from defining a variable. The dim statement is also used. The method of defining a one-dimensional array is as follows:

dim array name (number of elements), everyone should pay attention here. The number of elements defined here is always one less than what you want, because the starting point of an array is data No. 0 instead of 1, so everyone must be careful: You need If you need 10 data, define "9", if you need 100 data, define 99, and so on. The elements of the array can be regarded as independent variables, and you can use them like independent variables. The amount of array elements may be millimeters. It doesn’t matter. For example, the first array element stores your age, and the second array element stores the sales volume of watermelons this year. However, this approach is not encouraged or even accepted. Don’t do it. Please define such a situation. Independent variables. The for statement is very useful in arrays. Remember for? It accumulates a variable. We can apply this variable in the array to read or fill the array elements in order. The above is such a variable. Example. Arrays are actually very simple things (in the BASIC language). The difficult thing about arrays is how to fiddle with these loops and make them run according to your requirements. We will wait until the two-dimensional array, but let's first look at how to manually fill the array.

  If you can’t think of this, then you’ve learned nothing:

dim name(7),str 'There are eight students in total. The str variable is used to store them as a string for output

for i=0 to 7

name(i)=inputbox("Please enter the name of the "th" & i+1 & "student")

str=str & " " & name(i)

next

msgbox(str)

  In this way we have a small database, and their data arrangement can be seen as follows:

  name(0),name(1),name(2).....name(7)

  You see, so I said we can think of it as "a line". When we learn file operations, we can output them to files. One-dimensional arrays have many uses. Let's take a look at a complex Example. We want to store three types of data: name, height, and grade of each student. Since the name is a string, the height may be a floating point number (a number with a decimal point), and the grade may be an integer, so we cannot put them Stored in an array (don’t forget that data structures can only store data of the same type), so we need to build 3 arrays. The following is a routine:

dim name(2), high(2), mark(2) 'Define three arrays to store the names, heights and scores of 3 people respectively

dim ctr 'Counter

for ctr=0 to 2

name(ctr)=inputbox("Please enter the name of the "th" & ctr+1 & "student")

high(ctr)=inputbox("Please enter the height of the "th" & ctr+1 & "student")

mark(ctr)=inputbox("Please enter the score of the "th" & ctr+1 & "student")

next

  OK, we have filled in the data. Now our little database can only be entered in order. We want to make it look a little bit fancy. Let's design a query function for it:

'Follow the above procedure

dim cname, temp 'The name to be queried, and a temporary variable used to store the location of the data

cname=inputbox("Please enter the name you want to query:")

for ctr=0 to 2 'Traverse all members of the name array and find the name to be queried

if name(ctr)=cname then

temp=ctr 'Record data location

exit for 'Exit the loop, the same as exit do

end if 'Don't forget end if

next

msgbox("Name:" & name(temp) & " " & "Height:" & high(temp) & " " & "Score:" & mark(temp))

  Hehe, it's interesting. In fact, in this program, the temp variable is completely unnecessary, just to illustrate the problem more clearly. Because the value of the ctr variable will not change after exit for, and the corresponding data stored in the array is exactly Location, this temp variable is written to take care of friends who want to learn C++ in the future (C++ can declare new variables in the for statement, which are only valid in this for structure, so they cannot be accessed externally). In other words, it can be simplified to as follows:

dim cname

cname=inputbox("Please enter the name you want to query:")

for ctr=0 to 2

if name(ctr)=cname then exit for 'Because there is only exit for, there is no need for block if

next

msgbox("Name:" & name(ctr) & " " & "Height:" & high(ctr) & " " & "Score:" & mark(ctr))

  This is the most direct way. Re-read all the source codes above, and then write a few programs yourself. After fully understanding one-dimensional arrays and their applications, you can look at the two-dimensional arrays later. A two-dimensional array seems to be a one-dimensional array. The collection of is just like "the product of lines forms a surface". It consists of n one-dimensional arrays forming a two-dimensional array. This is a method that is easier for beginners to understand (it is more accurate to use the concept of "numbering" to understand it, because 4-dimensional The above arrays are more difficult to explain using Euclidean geometry concepts). Two-dimensional arrays are easy to explain. Let’s take a look:

dim a(2,2) 'Start from zero, there are 3 X 3 = 9 data in total

dim i,j 'requires two counters

for i=0 to 2

for j=0 to 2 'Use nested loops

a(i,j)="X"

next

next

  We created a two-dimensional array like this (those "," are what I used to divide the elements and do not exist). Do you understand the two-dimensional array? Not sure. Let's talk about it again.

Number 0 1 2

0 X,X,X

1 X,X,X

2 X,X,X

  Does the two-dimensional array look like a rectangle? (You can't see such a rectangle in the memory, it's just for your understanding). Each data has a number and is located by two numbers. This is very similar (very Like) if you are looking for a square on the chess board, we use "vertical coordinates" such as "C6" and "A2" to locate it. Yes, "vertical coordinates" are very precise. We need to use a two-dimensional array element It can be used like an ordinary variable, just specify the "anchoring point" of the array element, for example

a(0)(1)=1, b(2)(1)="Hello", and so on. It should be noted that two-dimensional arrays can only store elements of the same type, and the superscript (starting point) also starts from 0 Start. To calculate the number of elements in a two-dimensional array, just multiply the two subscripts + 1 (to get the actual value) and then multiply them. It is very similar to finding the area of ​​a rectangle.

  If we need to store the same type of data, we can use a two-dimensional array. For example, if we want to store the names, nationalities, and ethnicities of 5 people, we can use two-dimensional data.

dim info(4,2) 'There are five people in total, and there are 3 data types to be stored.

dim i,j

for i=0 to 4

for j=0 to 2

dim opt 'Define a variable to store data item prompts

select case j 'Determine what data should be entered

case 0

opt="name"

case 1

opt="nationality"

case 2

opt="ethnic"

end select

info(i,j)=inputbox("Please enter the number" & i+1 & "personal" & opt)

next

next

'Output is too troublesome, I'm too lazy to do it, you just know what's going on

  This eliminates the need to define three one-dimensional arrays.

  The definition and use of multi-dimensional arrays (three or more dimensions) are the same as those of two-dimensional arrays, but it is not easy to explain in Euclidean geometric space. Fortunately, we do not commonly use arrays with so many dimensions. Define a three-digit array: dim a(1,2,3) 'A total of 24 array elements.

  Today I have to move (I like Sengkang, but MM thinks the transportation is inconvenient, who doesn’t know she just wants to go shopping), and GF has to go to some experiment with her classmates and won’t get home until midnight, so I can only go by myself in the afternoon The escort car has been moved, 5555~~How pitiful. Please forgive me for writing less this time. I wrote while standing outside the library.

My legs are weak now~~~ I was originally going to talk about "Dynamic Arrays", but after thinking about it I'll leave it to the "Advanced Part".

Key points:

1) One-dimensional arrays are "lines", two-dimensional arrays are "surfaces", and three-dimensional arrays are "volumes" (multi-dimensional arrays are messy)

2) The subscript of the array starts from 0

3) The for loop plays a big role in the application of arrays. Two-dimensional arrays require nested loops.

Operation:

  Did you like the "Hundred Chicken Problem" last time? In the future, we will do this kind of questions that require brain use. You must do more of those simple practices!

1) Define an array containing 5 elements, all random integers (enter them randomly), and ask them to be arranged in order from largest to smallest.

2) There are two two-dimensional arrays a(4,4) and b(4,4) (the element values ​​are arbitrary), exchange the two arrays (all the element values ​​of the original a become b, and all the element values ​​of b become into a)

--------------------------------------------------------------------------------

Last article:

Today we are learning the last part of the basics: custom functions and procedures. We work with functions every day

When dealing with numbers, inputbox() is a function, msgbox() is a function, int() is also a function... These functions are all built-in in the system, and we can only use them and cannot change them. Today, I will teach you how to make a function yourself.

  First of all, we need to understand why we use functions. Let's talk in terms of "examples". Let's first look at an example: given two numbers, output the larger one.

dim a1,a2,b1,b2,c1,c2

a1=2:a2=4 '":" allows you to write multiple statements on one line

b1=32:b2=67

c1=12:c2=898

if a1>a2 then

msgbox(a1)

elseif a1<a2 then

msgbox(a2)

end if

if b1>b2 then

msgbox(b1)

elseif b1<b2 then

msgbox(b2)

end if

if c1>c2 then

msgbox(c1)

elseif c1<c2 then

msgbox(c2)

end if

  How troublesome, we copied the same comparison process several times. In the early days when the language was not structured (no procedures and functions), programmers did exactly this. They copied (Copy), and there was no clipboard in those days. This said, everyone had to re-enter the code. Later the work was simplified:

dim a1,a2,b1,b2,c1,c2

a1=2:a2=4

b1=32:b2=67

c1=12:c2=898

msgbox(co(a1,a2))

msgbox(co(b1,b2))

msgbox(co(c1,c2))

function co(t1,t2) 'We use function to define a new function

if t1>t2 then

co=t1 'Return the result through the method of "function name=expression"

elseif t2>t1 then

co=t2

end if

end function

We use a new keyword here: funciton. This keyword indicates the start of a new function. The format is:

funciton function name (parameter 1, parameter 2...parameter n) 'The list can be empty, but the parentheses cannot be omitted, and the parameters are separated by ","

...

exit funciton 'End function, not required

...

end function

  A function is a module that will only run when you call it. In other words, when you write a function and then do not call it in the program, then the function will never run. Generally speaking, when we write a program, according to:

main program

..

..

..

Function 1

..

..

Function 2

..

..

  Explain in detail: The most important things in a function are parameters and return values. Parameters are defined in () after the function name and are separated by ",". We also use "," when using parameters. At this point I Reminding me of something, a friend sent me a message yesterday and asked me:

  msgbox(name1,name2,name3)

  What's wrong with this? Why can't three variables be displayed at the same time? This is because you used ",". This symbol means that the three quantities you input are passed to the msgbox() function as three different parameters. The msgbox() function only The first parameter will be displayed, and the second parameter is to appear in the title bar. So you should use "&" or "+" to connect the three string variables and pass it to msgbox() as the first parameter. Function. When programmers talk about parameters, they often talk about "formal parameters" and "actual parameters". Let me explain. "Formal parameters" is the abbreviation of "formal parameters", and "actual parameters" are "actual parameters". The abbreviation of "parameter". The actual parameter refers to the quantity passed to the function when you call the function. It can be a variable or a constant (direct quantity). For example: 12,24 in co(12,24) is the actual parameter. The formal parameter is The variables you define when defining the function are used to "catch" the passed quantities. For example, function co(t1,t2)t1,t2 are formal parameters.

  In VBScript, parameter passing is a kind of passing by value, not passing by address (it doesn’t matter if you don’t understand, you will understand after learning pointers in C language), so the parameter passing we carry out is actually a variable assignment, for example When we call co(a1,a2), the program will actually perform one step: t1=a1,t2=a2. Also because of passing by value and address, VBScript can only return one value. Let’s first take a look at what is "Return". When a process calls another process (for example, the main program calls a function), control goes to the called process. When the process is completed, it will return to the place where it was called to continue execution. This It's called "return". When returning, you can bring a value called "return value" (this is the "popular" understanding). VBS inherits the tradition of basic and uses the method of "function name = return value" when returning. This "return value" refers to an expression (in programming, everything is an expression, such as variable a, constant 0, "Hello", c=1+2, etc. These are all expressions). For example, there is If the function is ht, the return method is: ht=the value you want to return. Note: After returning, the following statements will no longer be executed.

  I don’t need to talk about calling a function: variable = function name (parameter)

  Sometimes we don't need to return any value. At this time, we can use a structure called "subprogram". The difference between a subprogram or a process and a function is that: 1) there is no return value, 2) using Sub keyword definition, 3) Called through Call. Here is an example:

dim yname

name=inputbox("Please enter your name:")

call who(yname)

sub who(cname)

msgbox("Hello" & cname)

msgbox("Thank you for reading my course")

msgbox("This is the last lesson in the basics")

end sub

  You must understand, it's very simple. Exiting a process is the same as exiting a function: exit sub (function: exit function).

  It should be noted that subroutine (process) is a relatively special structure. Languages ​​such as C do not have this concept. Everything in C language is a function. Functions without return values ​​only need to be defined using the void modifier in C language. .

There is nothing more to talk about today. This is the end of the basics. Now that you have basic programming concepts (process-oriented structured programming), you can choose to learn another language (such as C or Pascal). Now the basics It will be of some help. You can also buy this book to continue learning VBS or learn about programming in more detail.

Part 4: Loop Structure

  Let’s take a look at a question first: The shopping mall performs daily settlement and is required to add up today’s turnover and enter a number each time. This question is actually very simple, but it is quite troublesome to complete this question based on the knowledge we have learned so far. Let's analyze it. First, we need to know the number of transactions so that we can control the number of inputs. However, this design is very inefficient and the program must be redesigned every day. Assume that 5 transactions were made today. The following is the source program:

dim sum

sum=0 'Initialize variables

sum=sum + int(inputbox("Please enter the transaction amount"))

'sum=sum+x This form takes out its own value, performs an operation, and then puts it back into itself. This method is very useful.' Function nesting is used here, and the return value of the inputbox is directly passed to the int function. , converted into an integer, the same below

sum=sum + int(inputbox("Please enter the transaction amount"))

sum=sum + int(inputbox("Please enter the transaction amount"))

sum=sum + int(inputbox("Please enter the transaction amount"))

sum=sum + int(inputbox("Please enter the transaction amount"))

msgbox(sum)

  Did you see that I designed the program by copying the calculation process 5 times? This kind of program can be used in places with few transactions such as automobile exchanges. If it is placed in a supermarket, it will have to be copied and pasted thousands of times. ? What we are talking about today can overcome this shortcoming. First, let us talk about the following Do...Loop statement.

  The structure of do...loop looks very simple, it is: do...loop, that's it. This structure continuously executes the statements between do and loop (scientific name: loop body),

Never stop. For example:

do

msgbox("This message will appear repeatedly. To stop the program, please use the task manager (Ctrl+Alt+Del) to kill the wscript process")

loop

  Run this program, and when you click and close a dialog box, another one will appear immediately. You can never finish clicking, there is always the next one. Who would run such a program? Unless it is to cause trouble for others (I have done this kind of thing) , so there is another statement in the do..loop structure: exit do. This statement will terminate the loop and jump to the statement after the loop to continue.

Execution. According to an example:

dim a 'Note: constants do not need to be declared in dim, otherwise an error will occur

const pass="123456" 'This is a string, please wrap it with "". Set the password as a constant and cannot be changed

do

a=inputbox("Please enter password")

if a=pass then

msgbox("Password verification successful")

exit do

end if

loop

  This program will keep asking you for your password until you enter the correct password. (If can be nested in another if, or in a loop, so be sure to use indentation to make it clear. various parts of the program). This program is very classic, and early programs did this. But we are Hackers, so

We understand the security of the system. This unlimited authentication program is easily cracked. We need to limit the number of authentications. The modified procedure is as follows

dim a,ctr

ctr=0 'Set counter

const pass="pas123_" 'The above one is a weak password, change it to a stronger one this time

do

if ctr=3 then

msgbox("The authentication limit has been reached, the authentication process is closed")

exit do

else

a=inputbox("Please enter password")

if a=pass then

msgbox("Authentication successful")

msgbox("(You can add a message here after success)")

exit do

else

ctr=ctr+1 'If the password is wrong, increase the error authentication count by one

msgbox("Authentication error, please check password")

end if

end if

loop

  Try running this program. When you get 3 errors, it will stop asking for the password again and close the program. The program used to limit the number of times for telnet authentication is similar to this. What you should pay attention to is the nested if statement. Read it carefully. This program may be difficult to understand, so please try to design a similar program yourself.

  In fact, to add verification function to do...loop, it is not necessary to use if, we can directly use do. Let me introduce the while keyword, while can be placed after do or loop, and then followed by Expression, when the value of the expression is true (the expression is established), the loop body will be run. Let's take a look at the modified

program"

dim a,ctr

ctr=0

const pass="pas123_"

do while ctr<3

a=inputbox("Please enter password")

if a=pass then

msgbox("Authentication successful")

msgbox("(You can add a message here after success)")

exit do

else

ctr=ctr+1 'If the password is wrong, increase the error authentication count by one

msgbox("Authentication error, please check password")

end if

loop

dim a,ctr

ctr=0

const pass="pas123_"

do

a=inputbox("Please enter password")

if a=pass then

msgbox("Authentication successful")

msgbox("(You can add a message here after success)")

exit do

else

ctr=ctr+1 'If the password is wrong, increase the error authentication count by one

msgbox("Authentication error, please check password")

end if

loop while ctr<3

  The function is the same, why should it be placed after the loop? You will know by changing the value of ctr to 3. The program after while will exit directly after do, and an authentication will be allowed after the loop, and the loop will not end until the end. The opposite of while is until. Its usage is the same as while, but it only executes the loop body when the value of the following expression is false (the expression is not true). Please try it yourself.

  ok, let’s look at another loop structure, for...next. This loop structure is based on counting and is also the most common loop structure in programming.

dim i

for i=0 to 5

msgbox(i)

next

  看到了吗?每次输出的i都是递增的, 但我们没有明确指出i要递增, 当i达到5的时候, 循环就结束了, 因为由0开始, 所以循环体执行了6次, 这一点很重要, 大部分东西都是从0开始而不是1. 这个程序也可以写成

do的形式:

dim i

i=0

do while i<5

msgbox(i)

i=i+1 '因为do不能自动计数, 必须手动加

loop

  怎么样, 还是for比较好用吧. for在编程中很有用途, 我们再举一个例子, 顺便讲一下嵌套循环.

dim i,j

for i=1 to 9

for i=1 to 9

str=str & i * j & " " '&是和并字符串的符号

next '每个next对应一个for

next

  看看运行结果, 是否令你会想起小学时代的数学老师(丑陋的嘴脸). 要注意, 这里有一个"大"的for, 和一个小的for, 当小的for执行完一个周期以后, 大的for才执行一次(换句话说, 大的for执行一次, 小的要执行9次), 所以一共执行了九九八十

一次. 在大的for里可以不仅仅是一个小的for, 也可以加上另外的语句. 我们来修改一下源程序:

dim i,j

for i=1 to 9

for i=1 to 9

str=str & i * j & " "

next '每个next对应一个for

str=str & vbCrlf 'vbCrlf相当于键盘上的回车键,因为你不能在键盘上输入,所以系统定义了一个默认的常量

next

  这次运行完成以后, 输出结果按照乘数进行了分割, 每小for运行完一次, 就换一行(通过vbcrlf).

  The content this time may be difficult for novices to understand. There is only one way to master it: practice more. In addition, I saw many people on the forum still asking: "What tool should I use to compile VBScript?" I was very angry. It has been explained in the article: Just use Notepad to edit the source code, and then save it as a program with a .vbs extension. Please don’t ask again. In addition, a domestic junk software "Super X Tyrant" has taken over the vbs extension, please uninstall that junk.

  Let’s summarize:

Key points:

1) Usage of do..loop and exit do

2) while executes the loop body when the expression is true, and vice versa until

3) for...next is a counting loop, and the counter is incremented each time it is executed.

4) The function and writing method of nested loops

4.5) & is used to connect strings

5) vbCrLf is equivalent to the Enter key on the keyboard

Operation:

1) There is such a question in the Chinese mathematics classic "Nine Chapters on Arithmetic": One hundred dollars buys one hundred chickens, a rooster costs 5 dollars, a hen costs 3 dollars, and two chicks cost 1 dollar (I use this data as a reference It’s from a programming book, but I remember there are 3 males, 1 female, and 1 chicken. No matter, just follow the instructions in the book.) How many ways can you buy these chickens? If you don’t understand. I said it in vernacular: Someone wanted to buy chickens. He bought exactly 100 chickens for 100 yuan. The prices are as follows: Male: 5$, Female: 3$, Small: 1$ for 2. I want you to find out how many chickens to sell in total. Method (How to match male and female babies). Please use loop to solve this problem.

PS: Today's article was written in a hurry, and most of the codes are not experimental. Please check it yourself. Also, I won’t tell you the answer to the last assignment. I don’t know if you like to do this kind of questions, or the simpler ones before?

--------------------------------------------------------------------------------

Article 5:

Today we’ll look at the last topic of the language itself: arrays.

  To understand "array", I think another translation of this concept is easier to learn: "array", yes, an array is an array, an array of data. The simplest example is a database system, assuming you want to store For the English scores of 20 students, if you did not use arrays, you would have to create 20 different variables, which would be exhausting. An array is a group of data (or n groups) of the same type (important!), used to store related quantities. The simplest array is a one-dimensional array, let's learn about it first.

  What is a one-dimensional array? Below 3 dimensions, you can use geometric knowledge to understand the concept of "dimension". One dimension is equivalent to a line, two dimensions is a rectangle, and three dimensions is a cuboid. I know it is very strange to say this. Abstractly, it will be easier to understand if we first take an example of a one-dimensional array.

dim a(9) 'Start from zero

for i=0 to 9

a(i)=i 'Fill each array element

msgbox(a(i)) 'Output array elements

next

  We can see that the method of defining an array is no different from defining a variable. The dim statement is also used. The method of defining a one-dimensional array is as follows:

dim array name (number of elements), everyone should pay attention here. The number of elements defined here is always one less than what you want, because the starting point of an array is data No. 0 instead of 1, so everyone must be careful: You need If you need 10 data, define "9", if you need 100 data, define 99, and so on. The elements of the array can be regarded as independent variables, and you can use them like independent variables. The amount of array elements may be millimeters. It doesn’t matter. For example, the first array element stores your age, and the second array element stores the sales volume of watermelons this year. However, this approach is not encouraged or even accepted. Don’t do it. Please define such a situation. Independent variables. The for statement is very useful in arrays. Remember for? It accumulates a variable. We can apply this variable in the array to read or fill the array elements in order. The above is such a variable. Example. Arrays are actually very simple things (in the BASIC language). The difficult thing about arrays is how to fiddle with these loops and make them run according to your requirements. We will wait until the two-dimensional array, but let's first look at how to manually fill the array.

  If you can’t think of this, then you’ve learned nothing:

dim name(7),str 'There are eight students in total. The str variable is used to store them as a string for output

for i=0 to 7

name(i)=inputbox("Please enter the name of the "th" & i+1 & "student")

str=str & " " & name(i)

next

msgbox(str)

  In this way we have a small database, and their data arrangement can be seen as follows:

  name(0),name(1),name(2).....name(7)

  You see, so I said we can think of it as "a line". When we learn file operations, we can output them to files. One-dimensional arrays have many uses. Let's take a look at a complex Example. We want to store three types of data: name, height, and grade of each student. Since the name is a string, the height may be a floating point number (a number with a decimal point), and the grade may be an integer, so we cannot put them Stored in an array (don’t forget that data structures can only store data of the same type), so we need to build 3 arrays. The following is a routine:

dim name(2), high(2), mark(2) '定义三个数组分别储存3个人的名字, 身高和得分

dim ctr '计数器

for ctr=0 to 2

name(ctr)=inputbox("请输入第" & ctr+1 & "个学生的姓名")

high(ctr)=inputbox("请输入第" & ctr+1 & "个学生的身高")

mark(ctr)=inputbox("请输入第" & ctr+1 & "个学生的得分")

next

  OK, we have filled in the data. Now our little database can only be entered in order. We want to make it look a little bit fancy. Let's design a query function for it:

'Follow the above procedure

dim cname, temp '要查询的名字, 和一个临时变量, 用来储存数据的位置

cname=inputbox("请输入你要查询的名字:")

for ctr=0 to 2 '遍历所有name数组的成员, 寻找要查询的名字

if name(ctr)=cname then

temp=ctr '记录数据位置

exit for '退出循环, 和exit do的用法一样

end if '不要忘了end if

next

msgbox("姓名:" & name(temp) & " " & "身高:" & high(temp) & " " & "得分:" & mark(temp))

  Hehe, it's interesting. In fact, in this program, the temp variable is completely unnecessary, just to illustrate the problem more clearly. Because the value of the ctr variable will not change after exit for, and the corresponding data stored in the array is exactly Location, this temp variable is written to take care of friends who want to learn C++ in the future (C++ can declare new variables in the for statement, which are only valid in this for structure, so they cannot be accessed externally). In other words, it can be simplified to as follows:

dim cname

cname=inputbox("请输入你要查询的名字:")

for ctr=0 to 2

if name(ctr)=cname then exit for '因为只有exit for就不需要块if了

next

msgbox("姓名:" & name(ctr) & " " & "身高:" & high(ctr) & " " & "得分:" & mark(ctr))

  This is the most direct way. Re-read all the source codes above, and then write a few programs yourself. After fully understanding one-dimensional arrays and their applications, you can look at the two-dimensional arrays later. A two-dimensional array seems to be a one-dimensional array. The collection of is just like "the product of lines forms a surface". It consists of n one-dimensional arrays forming a two-dimensional array. This is a method that is easier for beginners to understand (it is more accurate to use the concept of "numbering" to understand it, because 4-dimensional The above arrays are more difficult to explain using Euclidean geometry concepts). Two-dimensional arrays are easy to explain. Let’s take a look:

dim a(2,2) 'Start from zero, there are 3 X 3 = 9 data in total

dim i,j 'requires two counters

for i=0 to 2

for j=0 to 2 'Use nested loops

a(i,j)="X"

next

next

  We created a two-dimensional array like this (those "," are what I used to divide the elements and do not exist). Do you understand the two-dimensional array? Not sure. Let's talk about it again.

Number 0 1 2

0 X,X,X

1 X,X,X

2 X,X,X

  Does the two-dimensional array look like a rectangle? (You can't see such a rectangle in the memory, it's just for your understanding). Each data has a number and is located by two numbers. This is very similar (very Like) if you are looking for a square on the chess board, we use "vertical coordinates" such as "C6" and "A2" to locate it. Yes, "vertical coordinates" are very precise. We need to use a two-dimensional array element It can be used like an ordinary variable, just specify the "anchoring point" of the array element, for example

a(0)(1)=1, b(2)(1)="Hello", and so on. It should be noted that two-dimensional arrays can only store elements of the same type, and the superscript (starting point) also starts from 0 Start. To calculate the number of elements in a two-dimensional array, just multiply the two subscripts + 1 (to get the actual value) and then multiply them. It is very similar to finding the area of ​​a rectangle.

  If we need to store the same type of data, we can use a two-dimensional array. For example, if we want to store the names, nationalities, and ethnicities of 5 people, we can use two-dimensional data.

dim info(4,2) 'There are five people in total, and there are 3 data types to be stored.

dim i,j

for i=0 to 4

for j=0 to 2

dim opt 'Define a variable to store data item prompts

select case j 'Determine what data should be entered

case 0

opt="name"

case 1

opt="nationality"

case 2

opt="ethnic"

end select

info(i,j)=inputbox("Please enter the number" & i+1 & "personal" & opt)

next

next

'Output is too troublesome, I'm too lazy to do it, you just know what's going on

  这样就不需要定义3个一维数组了.

  多位数组(三维以上)的定义和使用方法与二维数组一样, 但不太好在欧几里德几何空间里加以解释, 幸好我们并不太常用那么多维的数组.定义一个三位数组:dim a(1,2,3) '一共24各数组元素.

  今天因为要搬家(我喜欢Sengkang啊, 可是MM嫌交通不便, 谁不知道她只想去逛街),而GF要去和她的同学去参加什么试验半夜才回家, 所以下午我只能自己去押车搬家了, 5555~~好可怜, 这次就请大家原谅我少写一点, 我可是站在图书馆外写的啊,

现在腿都软了~~~ 本来还要讲"动态数组"的, 但想了想还是放到"进阶部分"再说吧.

要点:

1) 一维数组是"线", 二维数组是"面", 三维数组是"体" (多维数组就乱套)

2) 数组的下标从0开始

3) for循环在数组的应用中起了很大作用, 二维数组需要嵌套循环

作业:

  上次出的"百鸡问题", 大家喜欢吗? 以后我们就做这种需要动脑的题目, 那些简单的实践, 大家一定要多做!

1) 定义一个数组, 包含5个元素, 都是随机整数(随便输入), 要求把他们按照从大到小的顺序排列起来

2) 有两个二维数组a(4,4)和b(4,4) (元素值随便), 交换两个数组(原来的a的所有元素值变成b的, b的所有元素值变成a的)

--------------------------------------------------------------------------------

最后一篇:

今天我们学习基础篇的最后一个部分:自定义函数和过程. 我们每天都在和函

数打交道, inputbox()是函数, msgbox()是函数, int()也是函数...这些函数都是系统内建的, 我们只能用不能改. 今天, 我就教大家怎样自己制作一个函数.

  First of all, we need to understand why we use functions. Let's talk in terms of "examples". Let's first look at an example: given two numbers, output the larger one.

dim a1,a2,b1,b2,c1,c2

a1=2:a2=4 '":" allows you to write multiple statements on one line

b1=32:b2=67

c1=12:c2=898

if a1>a2 then

msgbox(a1)

elseif a1<a2 then

msgbox(a2)

end if

if b1>b2 then

msgbox(b1)

elseif b1<b2 then

msgbox(b2)

end if

if c1>c2 then

msgbox(c1)

elseif c1<c2 then

msgbox(c2)

end if

  How troublesome, we copied the same comparison process several times. In the early days when the language was not structured (no procedures and functions), programmers did exactly this. They copied (Copy), and there was no clipboard in those days. This said, everyone had to re-enter the code. Later the work was simplified:

dim a1,a2,b1,b2,c1,c2

a1=2:a2=4

b1=32:b2=67

c1=12:c2=898

msgbox(co(a1,a2))

msgbox(co(b1,b2))

msgbox(co(c1,c2))

function co(t1,t2) 'We use function to define a new function

if t1>t2 then

co=t1 'Return the result through the method of "function name=expression"

elseif t2>t1 then

co=t2

end if

end function

We use a new keyword here: funciton. This keyword indicates the start of a new function. The format is:

funciton function name (parameter 1, parameter 2...parameter n) 'The list can be empty, but the parentheses cannot be omitted, and the parameters are separated by ","

...

exit funciton 'End function, not required

...

end function

  A function is a module that will only run when you call it. In other words, when you write a function and then do not call it in the program, then the function will never run. Generally speaking, when we write a program, according to:

main program

..

..

..

Function 1

..

..

Function 2

..

..

  Explain in detail: The most important things in a function are parameters and return values. Parameters are defined in () after the function name and are separated by ",". We also use "," when using parameters. At this point I Reminding me of something, a friend sent me a message yesterday and asked me:

  msgbox(name1,name2,name3)

  What's wrong with this? Why can't three variables be displayed at the same time? This is because you used ",". This symbol means that the three quantities you input are passed to the msgbox() function as three different parameters. The msgbox() function only The first parameter will be displayed, and the second parameter is to appear in the title bar. So you should use "&" or "+" to connect the three string variables and pass it to msgbox() as the first parameter. Function. When programmers talk about parameters, they often talk about "formal parameters" and "actual parameters". Let me explain. "Formal parameters" is the abbreviation of "formal parameters", and "actual parameters" are "actual parameters". The abbreviation of "parameter". The actual parameter refers to the quantity passed to the function when you call the function. It can be a variable or a constant (direct quantity). For example: 12,24 in co(12,24) is the actual parameter. The formal parameter is The variables you define when defining the function are used to "catch" the passed quantities. For example, function co(t1,t2)t1,t2 are formal parameters.

  In VBScript, parameter passing is a kind of passing by value, not passing by address (it doesn’t matter if you don’t understand, you will understand after learning pointers in C language), so the parameter passing we carry out is actually a variable assignment, for example When we call co(a1,a2), the program will actually perform one step: t1=a1,t2=a2. Also because of passing by value and address, VBScript can only return one value. Let’s first take a look at what is "Return". When a process calls another process (for example, the main program calls a function), control goes to the called process. When the process is completed, it will return to the place where it was called to continue execution. This It's called "return". When returning, you can bring a value called "return value" (this is the "popular" understanding). VBS inherits the tradition of basic and uses the method of "function name = return value" when returning. This "return value" refers to an expression (in programming, everything is an expression, such as variable a, constant 0, "Hello", c=1+2, etc. These are all expressions). For example, there is If the function is ht, the return method is: ht=the value you want to return. Note: After returning, the following statements will no longer be executed.

  I don’t need to talk about calling a function: variable = function name (parameter)

  Sometimes we don't need to return any value. At this time, we can use a structure called "subprogram". The difference between a subprogram or a process and a function is that: 1) there is no return value, 2) using Sub keyword definition, 3) Called through Call. Here is an example:

dim yname

name=inputbox("Please enter your name:")

call who(yname)

sub who(cname)

msgbox("Hello" & cname)

msgbox("Thank you for reading my course")

msgbox("This is the last lesson in the basics")

end sub

  You must understand, it's very simple. Exiting a process is the same as exiting a function: exit sub (function: exit function).

  It should be noted that subroutine (process) is a relatively special structure. Languages ​​such as C do not have this concept. Everything in C language is a function. Functions without return values ​​only need to be defined using the void modifier in C language. .

  There is nothing more to talk about today. This is the end of the basics. Now that you have basic programming concepts (process-oriented structured programming), you can choose to learn another language (such as C or Pascal). Now the basics It will be of some help. You can also buy this book to continue learning VBS or learn about programming in more detail.

(End of article)

Guess you like

Origin blog.csdn.net/WELFSDAF/article/details/125011871