我正在尝试创建一个循环来检查A列中的所有单元格,如果它发现其中任何一个单元格中包含短语“ISAW”(如1314_ISAW_STUFF),那么它会更改列中相应单元格的值G要“遵守”。
我有以下代码,循环工作,Cells.Find选项应该工作,但它不会激活任何具有匹配条件的单元格。
Sub mytestsub()
Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")
Dim i As Integer
sh1.Activate
On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
sh1.Cells.Find("ISAW").Activate
If InStr(ActiveCell, "ISAW") > 0 Then
ActiveCell.Offset(, 7).Value = "COMPLIANT"
End If
Next i
MyError:
On Error GoTo -1
End Sub
任何帮助将不胜感激!
我修改了Tom慷慨提供的脚本,如下所示,但它现在似乎没有用。
Sub bugfix()
'QA N/A bugfix'
Dim fndCell As Range
Dim FirstAddress As String
Worksheets("Summary").Unprotect
With Worksheets("Summary")
.Activate
On Error GoTo MyError
Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
If Not fndCell Is Nothing Then
' uncomment if you really want to visually track the cells
'fndCell.Activate
FirstAddress = fndCell.Address
Do
fndCell.Offset(0, 6).Value = "N/A"
Set fndCell = .Cells.FindNext(fndCell)
Loop Until fndCell.Address = FirstAddress
End If
End With
Exit Sub
MyError:
On Error GoTo -1
End Sub
答案 0 :(得分:1)
几乎没有理由Activate
或使用ActiveCell
来检查某个值,或更改其他单元格的值。
相反,请使用完全限定的对象。
此外,在这种情况下不需要使用On Error GoTo MyError
,请参阅下面的代码。
<强>代码强>
Sub mytestsub()
Dim sh1 As Worksheet
Dim i As Long, LastRow As Long
Set sh1 = Worksheets("Sheet1")
With sh1
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column "A"
For i = 1 To LastRow
If InStr(.Range("A" & i).Value2, "ISAW") > 0 Then ' check if current cell in column "A" contains "ISAW"
.Range("G" & i).Value2 = "COMPLIANT" ' change the value at column "G"
End If
Next i
End With
End Sub
答案 1 :(得分:0)
使用Find
和FindNext
执行此操作。这将找到Sheet1
中包含"ISAW"
的所有单元格,并更新列G
中的值。此外,如果出现错误,请确保在错误处理过程之前Exit Sub
,否则无论是否有错误都会运行。
评论后更新
它没有做任何事情的原因是因为您的代码实际上有错误但是它被On Error GoTo MyError
屏蔽了。我已使用固定代码更新
Sub bugfix()
'QA N/A bugfix'
Dim fndCell As Range
Dim FirstAddress As String
With Worksheets("Summary")
.Unprotect
.Activate
On Error GoTo MyError
Set fndCell = .Columns(3).Find(what:="ISAW", lookat:=xlPart)
If Not fndCell Is Nothing Then
' uncomment if you really want to visually track the cells
'fndCell.Activate
FirstAddress = fndCell.Address
Do
fndCell.Offset(0, 6).Value = "N/A"
Set fndCell = .Columns(3).FindNext(fndCell)
Loop Until fndCell.Address = FirstAddress
End If
End With
Exit Sub
MyError:
On Error GoTo -1
End Sub
答案 2 :(得分:0)
我可以理解可以有充分的理由使用VBA,但我可以在G列的第一个数据单元中建议一个公式作为选项,然后复制下来
=IF(ISERR(FIND("ISAW",A1,1)),"","COMPLIANT")
如果找到它,则查找它的字符串,然后返回它的起始位置,如果没有,则返回#VALUE
。封装IF
语句将其转换为COMPLIIANT或为空。