2014-03-28 77 views
0

以下是用於在列B中完全搜索字符串「目標」的腳本。問題是它只找到第一個條目,如何找到B列中所有字符串「goal」的出現,然後提取其相應的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 
+0

優秀的資源在這裏:http://www.cpearson.com/excel/findall.aspx –

+0

@TimWilliams感謝您的鏈接。我在這裏得到的答案是它與find和findnext函數。 – user3145195

回答

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