2017-06-16 171 views
1

我有一個帶一堆頭文件的Excel表,但有些沒有破折號。 我需要他們都有破折號,除了總數。Excel VBA用公式中的答案替換單元格

例: Column Headers

我已經寫了將破折號添加到標題公式:

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

然而,問題是,我需要這在VBA宏,它需要用保持相同的格式替換現有的標題。

我不知道該怎麼寫,這是我走到這一步:

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 

感謝您的幫助!

+0

不知道我跟着你。如果您在單元格中添加公式,它將覆蓋單元格的內容。如果您將文本放入單元格中,它將覆蓋公式。我不確定您的公式編輯文本的工作原理。 – FreeMan

回答

1

這是你正在嘗試?我已經評論了代碼,但是如果您仍有問題,請隨時提問。

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 

截圖

enter image description here

+0

老兄,哇!這寫得很好。我接近完全錯誤,哈哈。我感到愚蠢。你的代碼非常乾淨,我必須學習如何像你一樣寫。這很漂亮。感謝您的幫助。 –

+0

很高興有幫助:) –

相關問題