Excel VBA用公式中的答案replace单元格

我有一堆excel表头,但有些没有破折号。 我需要他们都有破折号,除了总数。

例如: 列标题

我已经写了公式,将破折号添加到标题:

=IF(A1="","",IF(A1="TOTAL","TOTAL",REPLACE(SUBSTITUTE(A1,"-",""), 1, 0, "-"))) 

但是,问题是我需要在VBAmacros中,它需要保持相同的格式replace现有的标题。

我不知道如何写这个,这是我到目前为止:

 Sub AddDash() Dim MaxColumn As String MaxColumn = Range("AY1").End(xlToLeft) For i = 1 To TotalRows Formula = "=IF(A1="","",IF(A1="TOTAL","TOTAL",REPLACE(SUBSTITUTE(A1,"-",""), 1, 0, "-")))" Next i End Sub 

这可能吗?

我见过类似的东西,但是我不明白这足以让它适合我的情况

 With Sheet1 With Range(.Cells(3,3), .Cells(.Rows.Count,3).End(xlup)) With .Offset(0, Sheet1.UsedRange.Columns.Count +3) .FormulaR1C1 = "=REPLACE(REPLACE(SUBSTITUTE(RC3,""-"",""""), 9, 0, ""-""), 7, 0, ""-"")" End With .Value = .Offset(0, Sheet1.UsedRange.Columns.Count +3).Value .Offset(0, Sheet1.UsedRange.Columns.Count +3).EntireRow.Delete End With End With 

感谢您的帮助!

这是你正在尝试? 我已经评论了代码,但是如果你仍然有一个问题,随时可以问。

 Sub AddDash() Dim ws As Worksheet Dim lCol As Long, i As Long '~~> Change this to the relevant sheet Set ws = Sheet1 With ws '~~> Find the last column in row 1 lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column '~~> Loop through the columns in row 1 For i = 1 To lCol '~~> Check 1 : Cell is not empty '~~> Check 2 : Cell doesn't have TOTAL '~~> Check 3 : Cell Doesn't already have a Dash If Len(Trim(.Cells(1, i).Value)) <> 0 And _ UCase(Trim(.Cells(1, i).Value)) <> "TOTAL" And _ Left(Trim(.Cells(1, i).Value), 1) <> "-" Then '~~> Add Dash .Cells(1, i).Value = "-" & .Cells(1, i).Value End If Next i End With End Sub 

截图

在这里输入图像说明