zoukankan      html  css  js  c++  java
  • VBA 根据Find方法根据特定内容查找单元格

    http://club.excelhome.net/thread-940744-1-1.html   

    2. Find方法的语法
    [语法]
    <单元格区域>.Find (What,[After],[LookIn],[LookAt],[SearchOrder],[SearchDirection],[MatchCase],[MatchByte],[SearchFormat])
    '__________________________________________________________________________________________________
    <单元格区域>.Find (要查找的数据,开始查找的位置,查找的范围类型,完全匹配还是部分匹配,行列方式查找,向前向后查找,区分大小写,全角或半角,查找格式)

    (5)参数LookAt,可选。可以为以下常量之一:XlWhole或者xlPart,用来指定所查找的数据是与单元格内容完全匹配还是部分匹配,默认值为xlPart。对应于“查找与替换”对话框中,“单元格匹配”复选框。

    案例:根据工作表名称查找标题栏中的对应标题的单元格

    源表:

    VBA语句:

    Option Explicit
    Option Compare Text
    Sub 根据内容查找单元格()
        Dim sSheet As Worksheet
        Dim eachSheet As Worksheet
        Dim findRange As Range
        Dim columnCount As Integer
        
        Set sSheet = Worksheets("数据")
        '获取工作表总列数
        columnCount = sSheet.UsedRange.Cells.EntireColumn.Count
        
        For Each eachSheet In Worksheets
            '只查找A1单元格所在的整行
            Set findRange = sSheet.Range("A1").EntireRow.Find(eachSheet.Name, , , xlWhole)
            Debug.Print findRange.Column
        Next eachSheet
       
    End Sub

    改进版:

    Option Explicit
    Option Compare Text
    Sub 根据内容查找单元格()
        Dim sSheet As Worksheet
        Dim eachSheet As Worksheet
        Dim findRange As Range
        Dim columnCount As Integer
        
        Set sSheet = Worksheets("Sheet2")
        '获取工作表总列数
        columnCount = sSheet.UsedRange.Cells.EntireColumn.Count
        
        For Each eachSheet In Worksheets
            '只查找A1单元格所在的整行
            Set findRange = sSheet.Range("A1").EntireRow.Find(eachSheet.Name, , , xlWhole)
            '可能找不到符合的单元格,因此使用前先判断下
            If Not findRange Is Nothing Then
               Debug.Print findRange.Column
            End If
        Next eachSheet
       
    End Sub

    如果可能存在没有找到的情况,如果直接使用它,没有找到就会导致程序报错,不过可以利用报错来终止程序运行,相当于抛出运行时异常,提示用户需要检查错误,也是一种策略,所以使用时根据需要综合考虑上面2种方案吧


    运行后:

    https://www.cnblogs.com/xpvincent/p/7424694.html  VBA中FIND方法的使用说明,不错的

  • 相关阅读:
    常用知识点集合
    LeetCode 66 Plus One
    LeetCode 88 Merge Sorted Array
    LeetCode 27 Remove Element
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 448 Find All Numbers Disappeared in an Array
    LeetCode 219 Contains Duplicate II
    LeetCode 118 Pascal's Triangle
    LeetCode 119 Pascal's Triangle II
    LeetCode 1 Two Sum
  • 原文地址:https://www.cnblogs.com/onelikeone/p/10202459.html
Copyright © 2011-2022 走看看