2016-03-24 58 views
0

我期待凝聚我的剧本,因为我仍然有很长的路要走,即使复制和粘贴这将花费我很长时间。我只是想缩小查找/替换函数凝聚查找/替换Excel脚本

Function ZoneChanges() 

Dim MyCell As range 

Worksheets("Sheet1").Activate 
Set MyCell = Application.InputBox(Prompt:="Select a cell", Type:=8) 

MyCell.Replace What:="EE", Replacement:="DA", LookAt:=xlPart, _ 
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
     ReplaceFormat:=False 
MyCell.Replace What:="EF", Replacement:="DB", LookAt:=xlPart, _ 
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
     ReplaceFormat:=False 

MyCell.Replace What:="EG", Replacement:="DC", LookAt:=xlPart, _ 
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
     ReplaceFormat:=False 

MyCell.Replace What:="EH", Replacement:="DD", LookAt:=xlPart, _ 
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
     ReplaceFormat:=False 

End Function 

谢谢!

+0

应该迁移到[codereview.stackexchange.com(http://codereview.stackexchange.com) –

+1

它可能是最好先尝试代码评审前落实JapanDave建议的修改,因为有关于复制粘贴的代码,除了“代替数据集上的循环”外, – Phrancis

回答

3

如果你必须做多个查找和替换,你可以把所有的值放在数组中并运行一个循环。问题是,这会比现在慢。但是,纯粹为了缩短代码,你可以做到这一点。

Function ZoneChanges() 

Dim MyCell As Range 
Dim arrWhat, arrRep, i As Long 

Worksheets("Sheet1").Activate 
Set MyCell = Application.InputBox(prompt:="Select a cell", Type:=8) 
arrWhat = Array("EE", "EF", "EG", "EH"): arrRep = Array("DA", "DB", "DC", "DD") 
    For i = LBound(arrWhat) To UBound(arrWhat) 
     MyCell.Replace What:=arrWhat(i), Replacement:=arrRep(i), LookAt:=xlPart, _ 
      SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
      ReplaceFormat:=False 
    Next 

End Function