VBS教程:函数-CreateObject 函数


VBS教程:函数-CreateObject 函数

文章插图
CreateObject
函数
创建并返回对
Automation
对象的引用 。
CreateObject(servername.typename
[,
location])
参数
servername
必选项 。提供对象的应用程序名称 。
typename
必选项 。要创建的对象类型或类 。
location
可选项 。对象所在的网络服务器将被创建 。
说明
Automation
服务器至少提供一种对象类型 。例如,字处理应用程序可以提供应用程序对象、文档对象和工具条对象 。
要创建
Automation
对象,将
CreateObject
函数返回的对象赋值给某对象变量:
Dim
ExcelSheetSet
ExcelSheet
=
CreateObject("Excel.Sheet")
上述代码启动创建对象(在此实例中,是
Microsoft
Excel
电子表格)的应用程序 。对象创建后,就可以在代码中使用定义的对象变量引用此对象 。在下面的示例中,可使用对象变量、ExcelSheet
和其他
Excel
对象,包括
Application
对象和
Cells
集合访问新对象的属性和方法 。例如:
'
Make
Excel
visible
through
the
Application
object.ExcelSheet.Application.Visible
=
True'
Place
some
text
in
the
first
cell
of
the
sheet.ExcelSheet.ActiveSheet.Cells(1,1).Value
=
"This
is
column
A,
row
1"'
Save
the
sheet.ExcelSheet.SaveAs
"C:\DOCS\TEST.XLS"'
Close
Excel
with
the
Quit
method
on
the
Application
object.ExcelSheet.Application.Quit'
Release
the
object
variable.Set
ExcelSheet
=
Nothing
在远程服务器上创建一个对象,当
Internet
安全关闭时只能完成 。通过传递计算机名到
CreateObject
服务器名的参数,能在远程网络上创建对象 。该名称如同共享部份的机器名 。例如网络共享名命名为:
"\\myserver\public",
servername

"myserver" 。另外,只能指定
servername
使用
DNS
格式或
IP
地址 。
以下代码返回运行在命名为"myserver"的远程网络计算机上
Excel
实例的版本号
:
Function
GetVersion
Dim
XLApp
Set
XLApp
=
CreateObject("Excel.Application",
"MyServer")
GetVersion
=
XLApp.VersionEnd
Function
错误发生在指定的远程服务器不存在或无法找到 。
InStr
函数
返回某字符串在另一字符串中第一次出现的位置 。
InStr([start,
]string1,
string2[,
compare])
参数
start
可选项 。数值表达式,用于设置每次搜索的开始位置 。如果省略,将从第一个字符的位置开始搜索 。如果
start
包含
Null,则会出现错误 。如果已指定
compare,则必须要有
start
参数 。
string1
必选项 。接受搜索的字符串表达式 。
string2
必选项 。要搜索的字符串表达式 。
compare
可选项 。指示在计算子字符串时使用的比较类型的数值 。有关数值,请参阅“设置”部分 。如果省略,将执行二进制比较 。
设置
compare
参数可以有以下值:
常数值描述vbBinaryCompare0执行二进制比较 。vbTextCompare1执行文本比较 。
返回值
InStr
函数返回以下值:
如果InStr
返回string1
为零长度0string1

NullNullstring2
为零长度startstring2

NullNullstring2
没有找到0在
string1
中找到
string2找到匹配字符串的位置start
>
Len(string2)0
说明
下面的示例利用
InStr
搜索字符串:
Dim
SearchString,
SearchChar,
MyPosSearchString
="XXpXXpXXPXXP"'
String
to
search
in.SearchChar
=
"P"'
Search
for
"P".MyPos
=
Instr(4,
SearchString,
SearchChar,
1)'
A
textual
comparison
starting
at
position
4.
Returns
6.MyPos
=
Instr(1,
SearchString,
SearchChar,
0)'
A
binary
comparison
starting
at
position
1.
Returns
9.
MyPos
=
Instr(SearchString,
SearchChar)'

推荐阅读