[英]select each cell from a column and loop through a column in another workbook if it exists Excel VBA Macro
[英]Excel VBA - Loop through a column of cells and search for each cell value in the workbook
我需要創建一個宏,循環遍歷包含字符串的選定單元格列表,並獲取每個字符串並在整個工作簿中搜索該字符串。 如果找到該字符串,則子應該退出並且應該選擇找到的字符串,否則移動到下一個要找到的字符串,直到列表的末尾。
當我運行我的代碼時,當找到列表中的字符串並且它不會轉到該單元格時,sub 不會退出。
Option Explicit
Dim sheetCount As Integer
Dim datatoFind
Sub Button1_Click()
Find_File
End Sub
Private Sub Find_File()
Dim c As Range
Dim counter As Integer
Dim currentSheet As Integer
Dim notFound As Boolean
notFound = True
For Each c In Selection.Cells
On Error Resume Next
currentSheet = ActiveSheet.Index
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
Cells.Find(What:=datatoFind, After:=ActiveCell, LookIn:=xlValues, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
If InStr(1, StrConv(ActiveCell.Value, vbLowerCase), datatoFind) Then
notFound = False
Sheets(counter).Activate
Range("datatoFind").Select
Exit For
End If
Next counter
If notFound = True Then
MsgBox ("Value not found")
Sheets(counter).Activate
Else
Exit Sub
End If
Next c
End Sub
任何幫助深表感謝!
如果是我的代碼,我會有所不同,但不會戲劇性地改變你的代碼
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
我希望它有助於理解...
有很多問題。 第一個是您正在搜索所有工作表。 第一個匹配項可能在包含匹配列的工作表中!
循環遍歷工作表時,排除包含要查找的項目列的工作表......................還有其他問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.