【问题标题】:"Declaration expected" in vbscriptvbscript 中的“预期声明”
【发布时间】:2012-02-20 13:32:13
【问题描述】:

我是 vbscript 的新手。我得到了错误

需要在 get_html 上声明

在我的代码的底部。我实际上是在尝试为变量get_html 声明一个值(这是一个 url)。我该如何解决这个问题?

Module Module1

Sub Main()

End Sub
Sub get_html(ByVal up_http, ByVal down_http)
    Dim xmlhttp : xmlhttp = CreateObject("msxml2.xmlhttp.3.0")
    xmlhttp.open("get", up_http, False)
    xmlhttp.send()

    Dim fso : fso = CreateObject("scripting.filesystemobject")

    Dim newfile : newfile = fso.createtextfile(down_http, True)
    newfile.write(xmlhttp.responseText)

    newfile.close()

    newfile = Nothing
    xmlhttp = Nothing

End Sub
get_html _"http://www.somwwebsite.com", _"c:\downloads\website.html"

End Module

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    有一些语法错误。

    • 模块语句不是VBScript 的一部分。
    • 下划线可能会导致意外结果。见http://technet.microsoft.com/en-us/library/ee198844.aspx(在页面上搜索单词underscore
    • 调用 Sub 时不能使用括号(例如,xmlhttp.open 是 sub,不返回任何内容)。调用子例程有两种主要选择。 sub_proc param1, param2Call sub_proc(param1, param2)
    • 赋值运算符“=”对于对象来说是不够的。你应该 使用Set 声明。它将对象引用分配给 变量。

    响应可能以 utf-8 编码返回。但是,FSO 对 utf-8 并不满意。另一种选择是将响应写为 unicode(将True 作为第三个参数传递给CreateTextFile) 但输出大小将大于应有的大小。因此我更喜欢使用Stream 对象。
    我已经修改了你的代码。请考虑。

    'Requeired Constants
    Const adSaveCreateNotExist = 1 'only creates if not exists
    Const adSaveCreateOverWrite = 2 'overwrites or creates if not exists
    Const adTypeBinary = 1
    
    Sub get_html(ByVal up_http, ByVal down_http)
        Dim xmlhttp, varBody
        Set xmlhttp = CreateObject("msxml2.xmlhttp.3.0")
            xmlhttp.open "GET", up_http, False
            xmlhttp.send
            varBody = xmlhttp.responseBody
        Set xmlhttp = Nothing
        Dim str
        Set str = CreateObject("Adodb.Stream")
            str.Type = adTypeBinary
            str.Open
            str.Write varBody
            str.SaveToFile down_http, adSaveCreateOverWrite
            str.Close
        Set str = Nothing
    End Sub
    
    get_html "http://stackoverflow.com", "c:\downloads\website.html"
    

    【讨论】:

    • 我得到这个错误在调用 Sub 时不能使用括号,我该怎么做才能解决它,请帮助我是初学者
    • codeSub_proc get_html(ByVal up_http, ByVal down_http) 是这样的吗?
    • 这只是“调用子”语法示例,sub_proc 只是示例子名称。
    【解决方案2】:

    您可能希望将您的呼叫转移到 get_html,以便从您的 Main 子例程 (Sub Main()) 中进行呼叫。例如:

    Sub Main()
      get_html _"http://www.somwwebsite.com", _"c:\downloads\website.html"
    End Sub
    

    AFAIK,您不能直接在模块内进行函数调用。

    【讨论】:

    • 我收到此错误:未为参数“公共子 get_html 的 down_htttp(up_http 作为对象,down_http 作为对象)”指定参数。像你说的那样改变代码之后。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2018-06-12
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多