使用Excel VBA格式化单元格

我想添加0.00,如果单元格的值不是空的,而不是0.下面的代码,我正在尝试,但不工作:

For x = 1 To ActiveWorkbook.Sheets.Count Step 1 With ActiveWorkbook.Worksheets(x).Range("A1:Z30") Set FinColumn = .Find(What:="price", AFter:=.Cells(1, 1), LookIn:=xlValues, LookAt _ :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) If FinColumn Is Nothing Then Else I = FinColumn.Row + 1 c = FinColumn.Column **problem with below Do loop,no clues how to do** **Do Until .Cells(I, c).Value <> "" And .Cells(I, c).Value <> 0 .Cells(I, c).NumberFormat = "0.00" I = I + 1 Loop** End If End With Next x 

请提供符合以下条件的代码:我希望代码也可以在2007年的两个版本中使用,并且必须符合以下条件:

如果在excel中的数据如下所示:

 Emp Name Emp id Empsal Jhon 1 steve 2 2 mike 3 3.5 paul 4 0 gabriel 5 0.00 bush 6 null 

如果我运行macros,数据应该转换为Empsal列中的以下格式:

 Emp Name Emp id Empsal Jhon 1 0 steve 2 2 mike 3 3.50 paul 4 0 gabriel 5 0.00 bush 6 0 

谢谢,

Chaitu

我build议使用不使用VBA的自定义数字格式,例如:

 [=0]0;0.00 

或者如果你想要很好的大数字:

 [=0]0;[>=1000]# ### ###;0.00 

试用和testing(最快的方法)

此代码使用条件格式。 唯一的缺点是,这个代码将在Excel 2007中起作用:P所以,如果你有Excel 2003,那么这是行不通的。

 Option Explicit Sub Sample() Dim x As Long Dim FinColumn As Range For x = 1 To ActiveWorkbook.Sheets.Count With ActiveWorkbook.Worksheets(x).Range("A1:Z30") Set FinColumn = .Find(What:="price", AFter:=.Cells(1, 1), _ LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Not FinColumn Is Nothing Then With Worksheets(x).Columns(FinColumn.Column) .NumberFormat = "General" .FormatConditions.Delete .FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _ Formula1:="=0" .FormatConditions(1).NumberFormat = "0.00" .FormatConditions(1).StopIfTrue = True End With End If End With Next x End Sub 

我认为你的意思是你想input"0.00"作为一个数值,但格式化看起来像“0.00”? 在这种情况下…

 .Cells(I, c).Value = 0 .Cells(I, c).NumberFormat = "0.00" 

你的循环:

  Do Until .Cells(I, c).Value <> "" And .Cells(I, c).Value <> 0 .Cells(I, c).Value = "0.00" I = I + 1 Loop 

循环直到find非空/非零值,并且无条件地将每个空单元设置为0:

 .Cells(I, c).Value = "0.00" 

(对于新工作表中的一般格式,除非您要求重新使用工作表或更改默认格式,否则此值将显示为0,而不是0.00。

如果你的意思是只设置非空值,你需要改变循环的限制条件不与次要的非空/空单元格testing冲突。 在那个循环中(即search非空),做一些独立的事情来检查每个单元格是否为非空。 (比如if / then / else来设置它的值)。

好吧,我想我知道你的意思了。 问题是你已经进入了一个不可能的Do Until Statement,因为你的单元格值不能同时为空AND 0,所以你可能会得到一个无限循环

下面,我简单地用ANDreplace你的AND

 Do Until .Cells(I, c).Value <> "" Or .Cells(I, c).Value <> 0 .Cells(I, c).Value = "0.00" I = I + 1 Loop 

或者,如果仍然不能覆盖它,请尝试使用<> Empty ,因为Empty将覆盖0和“”

 Do Until .Cells(I, c).Value <> Empty .Cells(I, c).Value = "0.00" I = I + 1 Loop