我有以下代码(缩短):
Dim rng As Range
Range("A1:K2000").Select
Set rng = Selection.Find(What:="MJ")
If Not rng Is Nothing Then
rng.Cells.Select
Dim furthest_row As Integer
rng.Offset(2000, -4).Select
Selection.End(xlUp).Select
If ActiveCell.Row > furthest_row Then
furthest_row = ActiveCell.Row
End If
rng.Offset(2000, -3).Select
Selection.End(xlUp).Select
If ActiveCell.Row > furthest_row Then
furthest_row = ActiveCell.Row
End If
Range("T9:T" & furthest_row).Select
.
.
.
ElseIf rng Is Nothing Then
Worksheets(ActiveSheet.Index + 1).Activate
End If
Next wrksheet
我需要修改代码:范围(“T9:T”&最远行).选择
用代码抵消和最远行多变的
像这样:
Range(rng.Offset(3, 15), 'whole current column') & furthest_row).Select
我选择了近十种组合,但都没有成功。
谢谢!
答案1
这并没有真正回答你的问题,但对于评论来说太长了。我不确定你想对 T 列做什么,或者你是否在寻找你找到的那一列右侧三列的东西MJ
如果你明确说明你想要做什么:我需要修改代码:Range("T9:T" & furthest_row).Select 使用 Offset 和 furthest_row 变量进行编码,我想答案是显而易见的,特别是在清理代码之后。
还有可能更好的方法来查找furthest_row
使用该Range.Find
方法,查找工作表上使用的最后一行;包含数据的最后一行、限制为几列的最后一行等。
但是您的代码存在许多问题,因此请仔细阅读内联注释。
'Always declare all variables
'Under Tools/Options/Editor SET to require variable declaration
'This will put Option Explicit at start of all newly created modules
Option Explicit
Sub terfuge()
Dim rng As Range
'I don't know of a reason to use Integer data type
'It is limited to 2^15 and internally gets converted to a Long
Dim furthest_row As Long
Dim rw As Long
'Rarely is there a reason to use Select, Selection, Active, Activate, etc.
' Use direct references instead
'It clutters the code and, if not very careful, can introduce bugs
Set rng = Range("A1:K2000").Find(What:="MJ") 'probably should add the other arguments,
'as most will default to the last used, which may not be what you want
If Not rng Is Nothing Then
'what happens if "MJ" is in column A:D? This next line will cause an error
rw = rng.Offset(2000, -4).End(xlUp).Row
If rw > furthest_row Then
furthest_row = rw
End If
rw = rng.Offset(2000, -3).End(xlUp).Row
If ActiveCell.Row > furthest_row Then
furthest_row = ActiveCell.Row
End If
Range("T9:T" & furthest_row).Select
'
'
'
ElseIf rng Is Nothing Then
Worksheets(ActiveSheet.Index + 1).Activate
End If
' Next wrksheet
End Sub
答案2
警告:
该代码是OP要求的部分解决方案,展示了如何使用变量,Row number
包括哦FF设置。
Sub FindRowNubmer()
Dim FindRow As Range
Set FindRow = Range("A:K").Find(What:="MJ", _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
MatchCase:=False)
Range("A1").Offset(FindRow.Row - 1, 1).Select
Range("A1").Offset(FindRow.Row + 1, 1).Value = "Found MJ in Row: " & FindRow.Row
End Sub
注意:
- Find 方法返回行号给
FindRow
变量。 FindRow.Row
读取行号。Range("A1).
,作为基准。Range("A1").Offset(FindRow.Row - 1, 1).Select
将单元格指针放在行上,代码找到搜索字符串
MJ
。
Offset(FindRow.Row + 1, 1).Value
- 处理 Row 操作并显示搜索字符串
Row Number
以及o可选代码行(为了更好地理解)。
您可以根据需要调整列、行和单元格引用。