【发布时间】:2012-04-30 20:08:53
【问题描述】:
我有一个打开的 Excel 文件并使用 VB 脚本,我只需要在 Excel 工作表中搜索列“A”,直到它与文本字符串匹配。当脚本找到匹配项时,我想查看找到匹配项的单元格的行号。 提前感谢您的帮助!
【问题讨论】:
-
显示您目前拥有的代码 - 添加到其中比猜测您的意思是 VBA 还是 vbscript 更容易。正如 Doug 提到的,它们有时被用来表示相同的东西。
我有一个打开的 Excel 文件并使用 VB 脚本,我只需要在 Excel 工作表中搜索列“A”,直到它与文本字符串匹配。当脚本找到匹配项时,我想查看找到匹配项的单元格的行号。 提前感谢您的帮助!
【问题讨论】:
这是在活动表的 A 列中查找“test2”的第一个实例的 VBA。您可以根据需要调整字符串和工作表。仅当整个单元格匹配时才算作匹配,例如“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
【讨论】:
excel-vba,因此我给了您该代码。有时人们会交替使用“vbscript”和“vba”。
vbscript 进行重大调整,即自动化Excel、删除变量的显式标注、为xlWhole 添加常量等。您需要更具体地说明什么你想要
LookAt:=xlWhole 参数。这就是@brettdj 所指的“常量”。这是一个猜测,但请尝试objSheet.Range("A:A").Find("1/1/2011",,,1,,,,,)。我认为这会起作用,因为LookAt 是 Find 的第四个参数,而 1 是 xlWhole 的数字(常数)等价物。
感谢您的样品。下面是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
【讨论】: