简体   繁体   English

使用VBA在Excel中搜索单元格

[英]Search for a Cell in Excel using VBA

Problem: I would like to find a value of a cell next to or below the cell content a text value for a workbook. 问题:我想在单元格内容旁边或下面找到一个单元格的值,作为工作簿的文本值。

Example: In Sheet2, I have two cells stand random (assume its index is unknown and total is not a defined name) 示例:在Sheet2中,我有两个单元格随机(假设其索引未知且total不是已定义的名称)

在此输入图像描述

I want to search for the value "200" stands next to the total and put it in sheet 2 (an active cell). 我想在总数旁边搜索值“200”并将其放在表2(活动单元格)中。 In case, there are multiple cell that contains the word "Total" list all of them and if possible, put the name of the sheet that contains the cell that I am looking for. 如果有多个单元格包含单词“Total”列表所有这些单词,如果可能的话,请输入包含我要查找的单元格的工作表的名称。 Value 200 Sheet2 价值200张2

在此输入图像描述

My Approach: 1. User input 我的方法:1。用户输入

在此输入图像描述

  1. Go to each cell and search for it. 转到每个单元格并搜索它。 This will take time if search for the whole limitation of cell in excel. 如果在excel中搜索单元格的整个限制,这将花费时间。 So the search only limit to 100 columns x 10000 rows. 因此搜索仅限于100列x 10000行。

  2. After find its index, offset to 1 columns to get the value 找到其索引后,偏移到1列即可获得该值

  3. Write the result ActiveCell.Value = Search_Value. 写结果ActiveCell.Value = Search_Value。 Then continue to search for the rest of sheets. 然后继续搜索剩余的工作表。 Offset 1 coloum and 1 row to write the second value... 偏移1 coloum和1行写第二个值...

Searching is a very difficult concept, and I truly have no idea how to do the search part. 搜索是一个非常困难的概念,我真的不知道如何进行搜索。 Please help 请帮忙

With Worksheets(1).Range("a1:a500")
    counter=0
    Set c = .Find("Total", lookin:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            counter=counter+1
            Worksheets(2).range("A1").offset(counter,0)=c.offset(0,1)
            Set c = .FindNext(c)
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
End With

firstaddress holds the location of the first cell found (so we know when to stop); firstaddress保存找到的第一个单元格的位置(所以我们知道何时停止); firstaddress.offset(0,1) will give you the value you are trying to save, so setting worksheet(2).range("a1").offset(counter,0) will list all the values it finds on the 2nd tab, from a1 down to however many it finds in the range firstaddress.offset(0,1)将为您提供要保存的值,因此设置工作表(2).range(“a1”)。offset(计数器,0)将列出它在第二个选项卡上找到的所有值,从a1到很多它在范围内找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM