搜索/查找单元格后,Excel VBA设置范围/单元格

时间:2019-05-14 17:55:46

标签: excel vba if-statement graph find

'我正在绘制图表。首先,我想在“ B”列中搜索关键字“ A-test”,然后从找到该词的位置选择10行和2列。我很难选择范围。请帮助在这种情况下如何使用“设置”功能。  这是我正在测试的宏

'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Sub Macro3()    
Macro3 Macro    
    Dim Ws As Worksheet    
    Dim i  As Long
    Dim k As Long
    Dim M As Range
    EndRow = ActiveWorkbook.Sheets("Sheet1").Range("B1").Offset(Sheets("Sheet1").Rows.Count - 1, 0).End(xlUp).Row
    i = 1
    For k = 2 To EndRow
        If Cells(k, 2) Like "*A*" Then
            Set M = Range("C1:L1", ActiveCell(i, 2).Offset(2, 10)) 'Difficult
            'Range("B1").Select 'test
            'Range("C1:L1,B4:L5").Select 'test
        End If
        'Cells(k, 2) Like "*A*"
    Next
End Sub
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

这里是数据。

Date    choice  Sample#1    Sample#2    Sample#3    Sample#4    Sample#5    Sample#6    Sample#7    Sample#8    Sample#9    Sample#10
2018/07/12 00:06:58 A-test  105259  103495  105225  103923  104536  103196  105020  104316  105317  103021
2018/07/12 00:07:03 B-test  105260  103848  105225  103923  104535  103196  105020  104316  105316  103021
2018/07/12 00:07:47 A-test  103108  101758  102702  101784  102592  101688  103971  103345  104344  101513
2018/07/12 00:07:51 B-test  103109  101410  102701  101785  102592  101688  103970  103346  104344  101513
2018/07/12 00:15:48 B-test  103108  101409  102702  101785  102593  101688  103971  103345  104345  101513
2018/07/12 00:40:16 B-test  103108  101408  102701  101785  102592  101688  103971  103345  104344  101513

1 个答案:

答案 0 :(得分:1)

使用Find方法更快。假定该文本仅出现一次,但是如果不是这种情况,则可以对其进行修改。

阅读this以了解为什么您可能不需要选择任何内容。

您可能想在Resize中交换10和2-不确定在那里想要什么。

Sub y()

Dim r As Range

Set r = Sheets("Sheet1").Range("B:B").Find(What:="A-test", Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

If Not r Is Nothing Then r.Resize(10, 2).Select '10 rows, 2 columns

End Sub

如果要引用更大的范围,请将其分配给范围变量,然后可以直接访问其属性和方法,而无需使用Select

Sub y()

Dim r As Range, rBig As Range

Set r = Sheets("Sheet1").Range("B:B").Find(What:="A-test", Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

If Not r Is Nothing Then
    Set rBig = r.Resize(10, 2)
End If

'then do stuff with the 10x2 range
'eg colour it red
rBig.Interior.Color = vbRed

End Sub