在列中搜索所有出现的字符串

时间:2014-03-28 02:54:32

标签: excel vbscript

以下是用于搜索字符串的脚本"目标"完全在B栏。问题是它只找到第一个条目,如何找到字符串的所有出现" goal"在B列中,然后提取其相应的D和G列值?

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False


Set objWorkbook = objExcel.Workbooks.Open("e:\csv\test1.csv")
Set objWorksheet = objWorkbook.Worksheets(1)

Set objRange = objWorksheet.Range("B1").EntireColumn

    strName = "Goal" 
    Set objSearch = objRange.Find(strName)
    If Not objSearch Is Nothing Then
        Wscript.Echo strName & " was found."
    End If

Set objExcel = Nothing
Set objWorkbook = Nothing

1 个答案:

答案 0 :(得分:0)

Set objExcel = CreateObject("Excel.Application")
    objExcel.Visible = False

Set objWorkbook = objExcel.Workbooks.Open("e:\csv\test1.csv")
Set objWorksheet = objWorkbook.Worksheets(1)

Set objRange = objWorksheet.Range("B1").EntireColumn

    numCountFinds = 0
    strName = "Goal" 
    Set objSearch = objRange.Find(strName)
    If Not objSearch Is Nothing Then
        numCountFinds = numCountFinds + 1
                strFirstAddress = objSearch.AddressLocal(False,False)
                str_D_Address = Replace( strFirstAddress, "B", "D")
                str_G_Address = Replace( strFirstAddress, "B", "G") 
            Wscript.Echo strName, numCountFinds, strFirstAddress, objWorksheet.Range(str_D_Address).Value, objWorksheet.Range(str_G_Address).Value
    End If
    Do Until (objSearch Is Nothing)
        Set objSearch = objRange.FindNext(objSearch)
        strNextAddress = objSearch.AddressLocal(False,False)
        If strNextAddress = strFirstAddress Then
            'we’ve found everything there is to find
                        '(first occurence reached again)
            Exit Do
        End If
        numCountFinds = numCountFinds + 1
                str_D_Address = Replace( strNextAddress, "B", "D")
                str_G_Address = Replace( strNextAddress, "B", "G") 
        Wscript.Echo strName, numCountFinds, strNextAddress, numCountFinds, objWorksheet.Range(str_D_Address).Value, objWorksheet.Range(str_G_Address).Value
    Loop
    Wscript.Echo strName & " " & CStr( numCountFinds) & ". times found"
Set objExcel = Nothing
Set objWorkbook = Nothing