【问题标题】:How to find the row number of a specific value in Excel using vbscript如何使用vbscript在Excel中查找特定值的行号
【发布时间】:2012-04-30 20:08:53
【问题描述】:

我有一个打开的 Excel 文件并使用 VB 脚本,我只需要在 Excel 工作表中搜索列“A”,直到它与文本字符串匹配。当脚本找到匹配项时,我想查看找到匹配项的单元格的行号。 提前感谢您的帮助!

【问题讨论】:

  • 显示您目前拥有的代码 - 添加到其中比猜测您的意思是 VBA 还是 vbscript 更容易。正如 Doug 提到的,它们有时被用来表示相同的东西。

标签: excel vbscript


【解决方案1】:

这是在活动表的 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”。
  • @buri kuri 该代码需要对vbscript 进行重大调整,即自动化Excel、删除变量的显式标注、为xlWhole 添加常量等。您需要更具体地说明什么你想要
  • 嗨朋友们,我用Doug的解决方案解决了find问题,这是另一个问题。当我尝试从 A 列中搜索“1/1/2011”时,它会带来“11/1/2011”行号,我不想像这样匹配。如何保持字符的精确匹配?顺便说一句,我使用了 vbscript,这是一行 --> Set FoundCell = objSheet.Range("A:A").Find("1/1/2011")
  • 您需要在其中获取LookAt:=xlWhole 参数。这就是@brettdj 所指的“常量”。这是一个猜测,但请尝试objSheet.Range("A:A").Find("1/1/2011",,,1,,,,,)。我认为这会起作用,因为LookAt 是 Find 的第四个参数,而 1 是 xlWhole 的数字(常数)等价物。
  • 这是我的问题的答案 --> objSheet.Range("A:A").Find("1/1/2011",,,1)
【解决方案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

【讨论】:

  • -1 for:未使用的 FSO,() 当调用 MsgBox 作为 Sub 时,对字符串 File_Path 和 WHAT_TO_FIND 使用 Set。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2011-10-28
  • 1970-01-01
相关资源
最近更新 更多