我正在尝试编写一个代码,该代码根据参考单元格中的值替换一系列单元格中公式中的文本。我已经解决了以下问题,但是仍然出现错误。任何建议都非常感谢!
Sub FindRepRegion()
If Active.Sheet.Range("J1") = "School" Then
Dim Findtext As String
Dim Replacetext As String
Findtext = "'Sheet1'!$B:$B"
Replacetext = "'Sheet1'!$AW:$AW"
ActiveSheet.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
ElseIf Active.Sheet.Range("J1") = "Grant" Then
Findtext = "'Sheet1'!$AX:$AX"
Replacetext = "'Sheet1'!$AW:$AW"
ActiveSheet.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
ElseIf Active.Sheet.Range("J1") = "Community School" Then
Findtext = "'Sheet1'!$AY:$AY"
Replacetext = "'Sheet1'!$AW:$AW"
ActiveSheet.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
Else
End If
End Sub
答案 0 :(得分:1)
@Pᴇʜ本质上回答了您的问题,但这是清理后的代码:
Option Explicit
Sub FindRepRegion()
Dim Findtext As String
Dim Replacetext As String
Replacetext = "'Sheet1'!$AW:$AW"
If ActiveSheet.Range("J1") = "School" Then
Findtext = "'Sheet1'!$B:$B"
ActiveSheet.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
ElseIf ActiveSheet.Range("J1") = "Grant" Then
Findtext = "'Sheet1'!$AX:$AX"
ActiveSheet.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
ElseIf ActiveSheet.Range("J1") = "Community School" Then
Findtext = "'Sheet1'!$AY:$AY"
ActiveSheet.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
End If
End Sub
但是,由于您的所有条件都在相同的范围内进行测试,我可以建议使用Select Case
吗?还添加了With
语句。
Option Explicit
Sub FindRepRegion()
Dim Findtext As String
Dim Replacetext As String
Replacetext = "'Sheet1'!$AW:$AW"
With ActiveSheet
Select Case .Range("J1")
Case "School"
Findtext = "'Sheet1'!$B:$B"
Case "Grant"
Findtext = "'Sheet1'!$AX:$AX"
Case "Community School"
Findtext = "'Sheet1'!$AY:$AY"
End Select
.Range("E3:G35").Replace what:=Findtext, replacement:=Replacetext, lookat:=xlPart, MatchCase:=False
End With
End Sub