2012-04-30 48 views
10

我有一個打開的Excel文件並使用VB腳本,我只需要在Excel表格中搜索列「A」,直到它匹配一個文本字符串。當腳本找到匹配項時,我想查看找到匹配項的單元格的行號。 感謝您的幫助提前!如何在Excel中使用vbscript查找特定值的行號

+1

顯示你到目前爲止的代碼 - 比猜測你是否真的指VBA或vbscript更容易。正如Doug提到的,它們有時被用來表示同樣的事情。 –

回答

20

這是VBA,在activesheet的A列中找到「test2」的第一個實例。您可以根據需要調整字符串和工作表。如果整個單元格匹配,它只會被視爲匹配,例如「test2222」不匹配。如果需要,請將lookat:=xlWhole位刪除:

Sub FindFirstInstance() 
Const WHAT_TO_FIND As String = "test2" 
Dim ws As Excel.Worksheet 
Dim FoundCell As Excel.Range 

Set ws = ActiveSheet 
Set FoundCell = ws.Range("A:A").Find(what:=WHAT_TO_FIND, lookat:=xlWhole) 
If Not FoundCell Is Nothing Then 
    MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row) 
Else 
    MsgBox (WHAT_TO_FIND & " not found") 
End If 
End Sub 
+0

那麼你可以使用相同的格式爲VBScript? –

+1

我不知道。由於您的標籤包含「excel-vba」,我向您提供了該代碼。有時候人們可以互換地使用「vbscript」和「vba」。 –

+2

@buri kuri該代碼需要對'vbscript'進行重要的調整,例如自動化Excel,刪除變量的顯式標註,爲'xlWhole'等添加常量等等。您需要更具體地瞭解您想要的內容 – brettdj

-2

感謝您的示例。下面是VBScript中的代碼

Dim FSO, oExcel, oData, FoundCell, WHAT_TO_FIND, File_Path 

WHAT_TO_FIND = "Report Summary" 
File_Path = "\\[Server]\[Drive$]\[Folder]\Data.xls" 

Set FSO = CreateObject("Scripting.FileSystemObject") 
Set oExcel = CreateObject("Excel.Application") 
Set oData = oExcel.Workbooks.Open(File_Path) 

Set FoundCell = oData.Worksheets("Sheet1").Range("A4:A20000").Find(WHAT_TO_FIND) 
If Not FoundCell Is Nothing Then 
    MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row) 
Else 
    MsgBox (WHAT_TO_FIND & " not found") 
End If 

Set File_Path = nothing 
Set WHAT_TO_FIND = nothing 
Set FoundCell = nothing 
Set oData = Nothing 
Set oExcel = Nothing 
Set FSO = Nothing 
+2

-1 for:未使用的FSO,()當調用MsgBox作爲Sub時,使用Set作爲字符串File_Path和WHAT_TO_FIND。 –

相關問題