用于replace格式但保留单元格值的VBA:部分解决

我正在尝试将VBA放在一起以search特定的单元格格式,然后更改该单元格格式。 我从这篇文章中得到了灵感( Excel VBA的值仍然是replace后的string格式 ),并希望从这篇文章中获得更多( Excel VBA – 添加一个自定义数字格式 ),但不能完全做到这一点。

我想要replace的单元格格式通常在以下6个格式中进行格式化

  1. <0
  2. <0.1
  3. <0.01
  4. <0.001
  5. <0.0001
  6. <0.00001

我想用正确的数字格式(“<0”,“<0.0”等)replace它们,并删除文本符号“<”,使它们显示为“<0”,但存储为一个数字用于计算。

到目前为止,我的方法是VBAreplacefunction。 对于一个给定的范围,我一直试图运行6种不同的replace为6种不同的格式,然后删除所有的文本符号为“<”,但我坚持以自己的价值取代单元格值:目前所有的单元格被replace相同的值(范围中的第一个单元格的值)。

我迄今为止开发的代码是:

Private Sub CommandButton6_Click() Dim range1 As Range With ActiveWorkbook.Worksheets("Sheet1") Set range1 = .[B2:B7] End With For Each cell In range1.Cells Dim Original0value As String Original0value = cell.Value Application.findformat.NumberFormat = "General" Application.ReplaceFormat.NumberFormat = "< 0" With range1 .Replace What:="< ?", Replacement:=Original0value, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchFormat:=True, ReplaceFormat:=True End With Next cell For Each cell In range1.Cells Dim Original1value As String Original1value = cell.Value Application.findformat.NumberFormat = "General" Application.ReplaceFormat.NumberFormat = "< 0.0" With range1 .Replace What:="< ???", Replacement:=Original1value, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchFormat:=True, ReplaceFormat:=True End With Next cell For Each cell In range1.Cells Dim Original2value As String Original2value = cell.Value Application.findformat.NumberFormat = "General" Application.ReplaceFormat.NumberFormat = "< 0.00" With range1 .Replace What:="< ????", Replacement:=Original2value, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchFormat:=True, ReplaceFormat:=True End With Next cell ' et cetera - I have only include the first 3 blocks of a possible 6 Cells.Replace What:="<", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False End Sub 

这给了我结果:

  1. <0
  2. <0.0
  3. <0.00
  4. 0.001
  5. 0.0001
  6. 0.00001

也就是说,前3个项目格式正确,但值已全部更改为0.由于我在每个块中使用“cell.Value”,我怀疑这是我的问题的来源,但不能完全弄清楚。 任何人都可以解释这一点吗?

您可以在自定义Range.NumberFormat属性中有两个条件和一个默认值。 您需要使用符号来允许附加小数位的可能性 。 使用自定义数字格式,

 With ActiveWorkbook.Worksheets("Sheet1") .range("B2:B7").NumberFormat = "[>1]< 0;[>0]< 0.0####; 0; @" 'maybe that should have been '.range("B2:B7").NumberFormat = "[>1]< 0;[>0]< 0.0####;< 0; @" End With 

B2:B7中的值应该只是数字; 不要input<符号。

cnf_decimals

由于文森特G的帮助,以前的问题解决了。

然而,在扩展的同时,我遇到了另一个问题:对于需要重新格式化的单元格的多个实例,VBA的工作方式与定制格式“<0.0”到“<0.00000”一样,但是由于某些原因,它遇到的所有其他格式化的实例的“<0”的第一个实例相同的值。

描述一下有点痛苦,请查看我在Dropbox上的示例电子表格 :表单中包含testing数据,VBA和问题描述。

干杯,基督徒