Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1756840
  • 博文数量: 600
  • 博客积分: 10581
  • 博客等级: 上将
  • 技术积分: 6205
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-06 10:13
文章分类
文章存档

2016年(2)

2015年(9)

2014年(8)

2013年(5)

2012年(8)

2011年(36)

2010年(34)

2009年(451)

2008年(47)

分类:

2009-10-11 11:16:38

来源:cww
经常有人问说:
x1=25
x2="ABC"
for i = 1 to 2
    str5 = "x" + cstr(i)
    debug.pring &str5  '&str5 想要印出 25与"ABC" 
next 
然而,如果用上面的程序来做,一定会错,&str5 是 XBase的用法,在vb中如何做呢?
这个问题便得使用VB6所提供的Script Control 来模拟XBase的Macro Evaluation (&)
,这个程序只是一个范例,没有 XBase那样的好用,您可以依需要来更动程序。

目前我只提供 字串、数值、日期三大类的Macro Evaluation 。

用法:

首先,将您有可能用上的Variable 以SetVariable()来设定,假设我有四个变数可能
做为Macro Evaluation的对象(分别是test1, test2, test3, test4),於是我给予以下
的设定:
Call SetVariable("test1", "50") 'test1 存"50"
Call SetVariable("test2", 2)    'test2存 2
Call SetVariable("test3", 3.5)  'test3存3.5
Call SetVariable("test4", CDate("02/01/98"))  'test4存日期

设完之後,用GetStrValue()来取出字串的值。

例如:
For j = 1 To 4
    str5 = "test" + CStr(j)
    i = GetStrValue(str5) '分别传入字串"test1", "test2", "test3", "test4"
    Debug.Print i 
Next

以下在Form, 需一个CommandBox 与一个Script Control
Private Sub Command1_Click()
Dim i, str5 As String, j As Long
Call SetVariable("test1", "50")
Call SetVariable("test2", 2)
Call SetVariable("test3", 3.5)
Call SetVariable("test4", CDate("02/01/98"))
For j = 1 To 4
    str5 = "test" + CStr(j)
    i = GetStrValue(str5)
    Debug.Print i
Next
End Sub

'设定做为Macro Evaluation 对象的变数
Private Sub SetVariable(ByVal var1 As String, value As Variant)
Dim codestr As String
If TypeName(value) = "String" Then
   codestr = var1 + "=" + """" + value + """"
Else
   If TypeName(value) = "Date" Then
      codestr = var1 + "= cdate(""" + CStr(value) + """)"
   Else
      codestr = var1 + "=" + CStr(value)
   End If
End If
ScriptControl1.ExecuteStatement codestr
End Sub

'传入想取得变数值的字串
Private Function GetStrValue(ByVal souStr As String) As Variant
Dim codestr As String
Dim i As Variant
i = sc.Eval(souStr)
If TypeName(i) = "String" Then
  codestr = "the_StrValue = " + """" + i + """"
Else
  If TypeName(i) = "Date" Then
     codestr = "the_StrValue = CDate(""" + CStr(i) + """)"
  Else
     codestr = "the_StrValue = " + CStr(i)
  End If
End If
ScriptControl1.ExecuteStatement codestr
GetStrValue = ScriptControl1.Eval("the_Strvalue")

End Function
阅读(470) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~