简体   繁体   English

VBA检查范围内的值

[英]VBA check for value in a range

I am trying to loop through a column and if cells = "what i'm lookng for" then do something. 我试图遍历一列,如果cells =“我要寻找的东西”,请执行某些操作。 I have this so far, where I'm off is in the if statement where I check for the "name": 到目前为止,我的工作是在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

OK Chris Maybe a bit of simplification is required but also a few assumptions. 好的,克里斯也许需要一些简化,但也需要一些假设。 It doesn't seem like LastCol is being used for anything - so let's assume this is the Column you want to loop through. 似乎LastCol并未用于任何事物-因此,我们假设这是您要循环遍历的列。 Your loop has fixed start and end values yet you are determining the LastRow - so let's assume you want to start from row 5 (in your code) and loop to the LastRow in the LastCol. 您的循环具有固定的开始和结束值,但您正在确定LastRow-因此,假设您要从第5行(在代码中)开始并循环到LastCol中的LastRow。 In order to determine LastCol you must have data in the row you are using to do this - so let's assume that there are values in row 1 in all columns up to column you want to loop say 16 (in your code). 为了确定LastCol,您必须在用于执行此操作的行中有数据-因此,假设在要循环播放的列中,所有列中的第1行中都有值(例如在代码中)。 If you want to (IF) test for a single (string) value in this case then you must arrange for your rngSource to be a single cell value. 如果要在这种情况下(IF)测试单个(字符串)值,则必须将rngSource安排为单个单元格值。 You also don't need to assign this to a variable unless you need to use it again. 您也不需要将其分配给变量,除非您需要再次使用它。 Finally, if you want to check for other values you may want to consider using a SELECT CASE structure in place of your IF THEN structure. 最后,如果要检查其他值,则可能需要考虑使用SELECT CASE结构代替IF THEN结构。 Have a look at the following and change my assumptions to meet your requirement - good luck. 请看以下内容,并更改我的假设以满足您的要求-祝您好运。

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

I'm guessing what you really want to do is loop through your range rngSource . 我猜你真的想做的是遍历范围rngSource So try 所以尝试

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

Pass value to find and Column where value need to be checked. 将值传递给find和需要检查值的列。 It will return row num if its found else return 0. 如果找到则返回行num,否则返回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

You can just do that with one line. 您只需要一行即可完成。

If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
'The value found in the given range
End If

Example: Search for "Canada" in column C of sheet named "Country" 示例:在名为“国家/地区”的工作表的C列中搜索“加拿大”

If Not IsError(Application.Match("Canada", Sheets("Country").Range("C:C"), 0)) Then
   'The value found in the given range
End If

I tried Hari's suggestion, but Application.Match works weird on range names (not recognizing them...) 我尝试了Hari的建议,但是Application.Match在范围名称上工作很奇怪(无法识别它们...)

Changed to: WorksheetFunction.Match(... It works, but when value is not present A runtime ERROR jumps before IsError(...) is evaluated. So I had to write a simple -no looping- solution: 更改为:WorksheetFunction.Match(...可以,但是当不存在值时,在评估IsError(...)之前会发生运行时错误跳转,因此我不得不编写一个简单的-no looping-解决方案:

dim Index as Long

Index = -1
On Error Resume Next
  Index = WorksheetFunction.Match(Target,Range("Edificios"), 0) 'look for Target value in range named: Edificios
On Error GoTo 0
If Index > 0 Then
    ' code for existing value found in Range @ Index row
End If

Remeber Excel functions first index = 1 (no zero based) 记住Excel函数的第一个索引= 1(不基于零)

Hope this helps. 希望这可以帮助。

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

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