gpt4 book ai didi

VBA 检查范围内的值

转载 作者:行者123 更新时间:2023-12-04 21:38:38 24 4
gpt4 key购买 nike

我正在尝试遍历一列,如果单元格 =“我在寻找什么”然后做点什么。
到目前为止,我有这个,我在 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

最佳答案

好的克里斯
也许需要一些简化,但也需要一些假设。
似乎 LastCol 没有被用于任何事情 - 所以让我们假设这是您想要循环的 Column 。
您的循环具有固定的开始和结束值,但您正在确定 LastRow - 所以让我们假设您要从第 5 行(在您的代码中)开始并循环到 LastCol 中的 LastRow。
为了确定 LastCol,您必须在用于执行此操作的行中有数据 - 所以让我们假设第 1 行中的所有列中都有值,直到您要循环的列 16(在您的代码中)。
如果您想在这种情况下(IF)测试单个(字符串)值,那么您必须将 rngSource 设置为单个单元格值。您也不需要将其分配给变量,除非您需要再次使用它。
最后,如果您想检查其他值,您可能需要考虑使用 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

关于VBA 检查范围内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25752167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com