在for循环中检索字符串时修剪字符串?

时间:2016-08-22 23:49:22

标签: excel vba excel-vba

我有这个for循环,用于从企业的Google地图页面中检索电话号码。

               For Each a In Array("_Xbe _ZWk kno-fv")
                aa = ""
                aa = IE.Document.getElementsByClassName(a)(0).innerText
                If Len(bb) > 0 Then
                Wksht.Cells(LngRow, 10) = aa
                Exit For
              End If

           Next

效果很好但电话号码的格式为(xx)x​​xxx xxxx。我希望它是xxxxxxxxxx。你如何在for循环中修剪和连接?

3 个答案:

答案 0 :(得分:2)

您需要更改Column的NumberFormat并使用replace来删除括号ans空格。

Wksht.Columns(10).NumberFormat = "0000000000"

For Each a In Array("_Xbe _ZWk kno-fv")
    aa = ""
    aa = IE.Document.getElementsByClassName(a)(0).innerText
    aa = Replace(aa, "(", "")
    aa = Replace(aa, ")", "")
    aa = Replace(aa, " ", "")

    If Len(bb) > 0 Then
        Wksht.Cells(LngRow, 10) = aa
        Exit For
    End If
Next

答案 1 :(得分:0)

尝试以下代码

 For Each a In Array("_Xbe _ZWk kno-fv")
            aa = ""
            aa = IE.Document.getElementsByClassName(a)(0).innerText
            If Len(aa) > 0 Then
            aa =trim(aa)
            aa = mid(aa, 2,2) & mid(aa,6,4)& right(aa,len(aa)-10)

            Wksht.Cells(LngRow, 10) = aa
            Exit For
          End If

       Next

答案 2 :(得分:0)

强制性正则表达式回答......

For Each a In Array("_Xbe _ZWk kno-fv")
    aa = vbNullString
    aa = IE.Document.getElementsByClassName(a)(0).innerText
    If Len(bb) > 0 Then
        With New RegExp
            .Pattern = "[^\d]"
            .Global = True
            Wksht.Cells(LngRow, 10) = .Replace(aa, vbNullString)
        End With
        Exit For
    End If
Next

注意:这需要引用Microsoft VBScript正则表达式,或者您可以使用With CreateObject("VBScript.RegExp")代替With New RegExp来使用后期绑定。