简体   繁体   English

录制宏时,根据单元格中的文本值选择范围

[英]Select a range based on text value in a cell when recording a Macro

I have a csv file I have recorded a macro for to manipulate the data of the CSV file as I need it. 我有一个csv文件,我记录了一个宏,用于在需要时操作CSV文件的数据。 Part of the macro looks for a cell containing the text "month index". 宏的一部分将查找包含文本“月份索引”的单元格。 Once this cell is located, a range is selected (A9,B50) for example. 定位此单元格后,将选择一个范围(例如A9,B50)。 The problem is, the "month index" cell can be located in A7, A8, A11 etc so the macro pulls the wrong data if the cell reference is difference. 问题在于,“月索引”单元格可以位于A7,A8,A11等中,因此,如果单元格引用不同,则宏会提取错误的数据。 The range I select is consistent once "month index" is found so I think I can use the offset instruction in someway but not sure. 一旦找到“月指数”,我选择的范围就是一致的,因此我认为我可以以某种方式使用偏移量指令,但不确定。

Currently my Macro that handles this bit looks like this: 当前,我的宏处理以下内容:

        Range("A1").Select     
        Cells.Find(What:="month index", After:=ActiveCell, LookIn:=xlFormulas, _    
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _        

MatchCase:=False, SearchFormat:=False).Activate     
        Range("A9:B9").Select     
        Range(Selection, Selection.End(xlDown)).Select     
        Selection.Cut 
  • Can anyone help me figure this out? 谁能帮我解决这个问题?

Using the Macro Recorder is great to get started on a task, however it adds a ton of extra code that is inefficient. 使用Macro Recorder很好地开始执行一项任务,但是它增加了很多效率低下的额外代码。 Learn how to Avoid Select/Activate . 了解如何避免选择/激活

You need to grab the row that 'Month index" appears in, since it is dynamic and moves, you can't just select the same range all the time, it needs to move based on the row found...try something along these lines. 您需要抓住“月份索引”出现的行,因为它是动态的并且在移动,所以您不能一直都选择相同的范围,它需要根据找到的行移动...尝试一些方法线。

Dim iRow as Integer, iMax as Integer

iRow = Cells.Find(What:="month index", After:=ActiveCell, LookIn:=xlFormulas, _    
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _        
    MatchCase:=False, SearchFormat:=False).Row

iMax = Cells(iRow, "A").End(XlDown).Row
Range("A" & iRow & ":B" & iMax).Cut 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM