VBA检查范围内的值

我试图通过一个列循环,如果细胞=“我在寻找什么”然后做一些事情。 我有这个到目前为止,我在哪里是在if语句中,我检查“名称”:

Option Explicit Sub test() Dim wksDest As Worksheet Dim wksSource As Worksheet Dim rngSource As Range Dim name As String Dim LastRow As Long Dim LastCol As Long Dim c As Long Application.ScreenUpdating = False Set wksSource = Worksheets("Sheet1") With wksSource LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column For c = 16 To 20 LastRow = .Cells(.Rows.Count, c).End(xlUp).Row Set rngSource = .Range(.Cells(5, 16), .Cells(LastRow, 16)) name = rngSource.Value If name = "mark" do something End If Next c End With Application.ScreenUpdating = True 'MsgBox "Done!", vbExclamation End Sub 

好的Chris也许需要一些简化,但也有一些假设。 它似乎并不像LastCol被用于任何事情 – 所以我们假设这是你想要循环的列。 你的循环有固定的开始和结束值,但是你正在确定LastRow – 所以我们假设你想从第5行开始(在你的代码中)并且循环到LastCol中的LastRow。 为了确定LastCol,你必须在你正在使用的行中有这样的数据 – 所以我们假设在第1行的所有列中你想要循环说16(在你的代码中)。 如果你想(IF)在这种情况下testing单个(string)值,那么你必须安排你的rngSource是一个单元值。 除非需要再次使用,否则也不需要将其分配给variables。 最后,如果你想检查其他值,你可能需要考虑使用SELECT CASE结构来代替IF THEN结构。 看看下面的内容,并改变我的假设,以满足您的要求 – 祝你好运。

 Sub test() Dim wksDest As Worksheet Dim wksSource As Worksheet Dim rngSource As Range Dim name As String Dim LastRow As Long Dim LastCol As Long Dim c As Long Application.ScreenUpdating = False Set wksSource = Worksheets("Sheet1") With wksSource LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column LastRow = .Cells(Rows.Count, LastCol).End(xlUp).Row FirstRow = 5 For c = FirstRow To LastRow If .Range(.Cells(c, LastCol), .Cells(c, LastCol)).Value = "Mark" Then MsgBox ("do something") End If Next c End With End Sub 

我猜你真正想要做的是循环你的范围rngSource 。 所以试试

 Set rngSource = .Range(.Cells(5, 16), .Cells(LastRow, 16)) for myCell in rngSource if myCell.Value = "mark" then do something end if next myCell 

通过值来查找和列需要检查的值。 它会返回行号如果它发现其他返回0。

 Function checkForValue(FindString As String,ColumnToCheck as String) As Long SheetLastRow = Sheets("Sheet1").Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).row With Sheets("Sheet1").Range("$" & ColumnToCheck & "$1:$" & ColumnToCheck & "$" & CStr(SheetLastRow) ) Set rng = .Find(What:=FindString, _ After:=.Cells(.Cells.Count), _ LookIn:=xlValues, _ lookat:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not rng Is Nothing Then checkForValue = rng.row 'return row its found 'write code you want. Else checkForValue = 0 End If End With End Function