如何getElementByID,但只是其中的一部分?

时间:2016-06-03 18:41:25

标签: excel internet-explorer vbscript getelementbyid

我使用getElementByID将数据从IE传输到Excel,但是如果fx的内部文本包含数字和文本并且只需要数字,或者如果有趣的部分是用红色写的,其余部分是黑色?你会按类或类型指定它,如果是,怎么做?

ws.Range("A1").Value = objExplorer.document.getElementByID("the ID of the element which includes unwanted characters").innerText

3 个答案:

答案 0 :(得分:0)

如果TEXT字符长度始终相同,您可以使用Replace(),Substitute(),Left(),Right()... 示例ABC123,CCC3456,DGF453454

如果TEXT字符长度不同,则使用以下VB代码创建UDF(用户定义的公式):

Public Function removeLetters(ByVal str As String) As String
    With CreateObject("vbscript.regexp")
        .ignorecase = True
        .Global = True
        .Pattern = "[a-z]"
        removeLetters = .Replace(str, "")
    End With
End Function

使用如下:

ws.Range("A1").Value = removeLetters(objExplorer.document.getElementByID("the ID of the element which includes unwanted characters").innerText)

**相应修改上述代码

由于

答案 1 :(得分:0)

这是一个基于Style.Color属性根据颜色获取文本的解决方案。我使用UDF FindWindow来获取指向现有网页的指针。

Public Sub FindRedOrGreenText()
    Dim ie          As Object
    Dim Element     As Object
    Dim Elements    As Object

    Set ie = FindWindow("URL", "trafficestimate.com")

    If Not ie Is Nothing Then
        Set Elements = ie.document.getelementbyid("ctl00_cphMainContent_ucGoogleMonthlyChart_pnlEstimateOnly").getelementsbyTagName("span")

        For Each Element In Elements
            If Element.Style.Color = "green" Then
                Debug.Print "Here is the green text! "; Element.innertext
            ElseIf Element.Style.Color = "red" Then
                Debug.Print "Here is the red text! "; Element.innertext
            End If
        Next Element
    End If

    Set Element = Nothing
    Set Elements = Nothing
    Set ie = Nothing
End Sub

Function FindWindow(SearchBy As String, SearchCriteria As String) As Object
    Dim Window      As Object

    For Each Window In CreateObject("Shell.Application").Windows
        If SearchBy = "URL" And Window.LocationUrl Like "*" & SearchCriteria & "*" Then
            Set FindWindow = Window
            Exit Function
        ElseIf SearchBy = "Name" And Window.LocationName Like "*" & SearchCriteria & "*" Then
            Set FindWindow = Window
            Exit Function
        End If
    Next Window

    Set FindWindow = Nothing
End Function

答案 2 :(得分:-1)

我认为你可能正在寻找的是一个正则表达式。如果您只想要内部文本的数字值,那么您可以使用

objExplorer.document.getElementByID("id").innerText.replace(/[^\d]/g, '')