Excel VBA - 循环遍历单元格列并搜索工作簿中的每个单元格值

时间:2016-05-28 22:17:02

标签: excel vba excel-vba macros

我需要创建一个循环遍历包含字符串的选定单元格列表的宏,并获取每个字符串并在整个工作簿中搜索该字符串。如果找到该字符串,则该子应该退出并且应该选择找到的字符串,否则移动到要找到的下一个字符串,直到列表的末尾。

当我运行我的代码时,当找到列表中的字符串并且它没有进入该单元格时,sub不会退出。

#include <iostream>
#include <vector>

using namespace std;

int main()
{
   vector<int> numbers;

   int in = rand() % 100 + 1;

   for (int i = 0; i < in; i++)
   {

      int n = rand() % 100 + 1;

      numbers.push_back(n);

      cout << "Number is: " << numbers[i];

      system("pause");
      return 0;
   }
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

如果是我的代码我将会有所不同,但不要改变你的代码

Public Sub Find_File()
Dim c As Range
Dim counter As Integer
Dim currentSheet As Integer
Dim notFound As Boolean
Dim datatoFind As String
Dim sheetCount As Integer
Dim cellFound As Range
Dim cellToFind As Range
Dim originalSheet As Worksheet

notFound = True
Set originalSheet = ActiveSheet
For Each c In Selection.Cells
    On Error Resume Next
    currentSheet = ActiveSheet.Index
    Set cellToFind = c
    datatoFind = StrConv(c.Value, vbLowerCase)
    If datatoFind = "" Then Exit Sub
    sheetCount = ActiveWorkbook.Sheets.Count
    If IsError(CDbl(datatoFind)) = False Then datatoFind = CDbl(datatoFind)
    For counter = 1 To sheetCount
        Sheets(counter).Activate
        Set cellFound = Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlValues, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)
        If Not cellFound Is Nothing Then
            If cellFound.Address <> cellToFind.Address And _
               cellFound.Parent.Name <> cellToFind.Parent.Name Then
                notFound = False
                cellFound.Activate
                GoTo WorksEnd
            End If
        End If
    Next counter
Next c
WorksEnd:
    If notFound = True Then
        originalSheet.Activate
        MsgBox ("Value not found")

    End If

End Sub

我希望有助于理解...

答案 1 :(得分:0)

有很多问题。第一个是您正在搜索所有工作表。第一场比赛可能在包含您的比赛列的工作表中!

在循环浏览工作表时,排除包含要找到的项目列的工作表...................还有其他问题