Excel VBA无法处理具有前导零的单元格

时间:2017-05-01 19:17:52

标签: excel vba excel-vba

我的任务是获取序列号的特定子集,编写替换,然后运行find&替换更大的序列号。我正在运行这个宏:

Sub multiFindandReplace()
  Dim myList As Range, myRange As Range, cel As Range
  Set myList = Sheets("Replacement Data").Range("B2:C4246")     
  'two column range with find/replace pairs 
  Set myRange = Sheets("Raw Data").Range("B2:B20000") 
  'range to be searched and replace 
  For Each cel In myList.Columns(1).Cells
    myRange.Replace What:=cel.Value, Replacement:=cel.Offset(0, 1).Value, LookAt:=xlWhole 
  Next cel
End Sub

该代码仅适用于没有前导零的条目。我需要保留前导零,但问题是主数据列表中的序列号并非全部以零开头,并非全部被替换,并且长度不同。我在下面附上了一小段样本数据:

Part #  Full Part #
4184    004184
4444    004444
100001  00100001
100002  00100002
100003  00100003
100004  00100004
100005  00100005
100006  00100006
100007  00100007
100008  00100008

此查找/替换列表为2000行。我需要搜索20,000个项目的列表并替换这2000行。任何帮助深表感谢。谢谢。

1 个答案:

答案 0 :(得分:0)

在填充前尝试将范围格式设置为文本:

Sub multiFindandReplace()
  Dim myList As Range, myRange As Range, cel As Range
  Set myList = Sheets("Replacement Data").Range("B2:C4246")     
  'two column range with find/replace pairs 
  Set myRange = Sheets("Raw Data").Range("B2:B20000") 
      myRange.NumberFormat = "@"  'this line should force text format and stop Excel removing the leading zeros
  'range to be searched and replace 
  For Each cel In myList.Columns(1).Cells
    myRange.Replace What:=cel.Value, Replacement:=cel.Offset(0, 1).Value, LookAt:=xlWhole 
  Next cel
End Sub