我正在尝试自己学习VBA,所以我正在做一些基本的事情来解决它。我现在想做的是在A列中查找“总计”一词,找到该词后,考虑下一个列中的值,然后使用If then语句判断B列中的数字是否为> 1,然后按C1“是”或B1“否”
Sub try5()
Set cell = Columns("A:A").Select
Selection.Find(What:="Total", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(columnOffset:=1).Activate.Select
If cell > 1 Then
Range("C1").Value = "yes"
Else
Range("C1").Value = "no"
End If
End Sub
代码的第一部分,如果我自己运行,但是VBA给我一个弹出窗口,说:“需要对象”,而如果我使用IF THEN语句运行,则说“类型不匹配”。
对不起,如果这不是菜鸟问题。
答案 0 :(得分:1)
尝试类似这样的方法。
Found
单元格设置为范围Found
= Nothing
,而逻辑测试Nothing > 1
毫无意义。Offset(r, c)
来导航r
行和c
列到找到的单元格的距离(这里我们想看1列,因此我们使用Offset(0,1)
= {{1 }}。然后,我们要看的是Col C(距离A的两列),因此我们使用Offset(,1)
来编写Offset(,2)
/ yes
no
我也不建议使用Sub try5()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim SearchRange As Range, Found As Range
Set SearchRange = ws.Range("A:A")
Set Found = SearchRange.Find(What:="Total", LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Found Is Nothing Then 'If a match is NOT found
MsgBox "'Total' Not Found in Range " & SearchRange.Address(False, False)
Else 'If a match is found
If Found.Offset(, 1) > 1 Then
Found.Offset(, 2) = "yes"
Else
Found.Offset(, 2) = "no"
End If
End If
End Sub
。您应该始终尝试找到一种方法来明确声明要修改的.Select
,Workbook
,Sheet
或Range
。为了更改,删除,移动,复制等,这些对象都不需Cell
或Active
。