close

新手VBA,多多指教

 

大綱:將字串中指定字元刪除

程式碼目標:將名字中第三個以上的空格刪除

EX.  字串:A B C D E →字串:A B CDE


STEP:
1.標記三格以上的修改目標字串

2.計算處理範圍

3.IF條件式:處理標記目標

4.找尋字串中空格位置

5.刪除指定位置的字元(空格)


'標記有三個空白以上的儲存格(標記為紅色底)
    With Application.ReplaceFormat.Interior
        .PatternColorIndex = xlAutomatic
        .Color = 255
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With


    Selection.Replace What:="* * * *", Replacement:=Selection.Text, LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=True

    '宣告有用變數

    Dim i As Integer      'IF迴圈用變數
    Dim str As String     '目標字串
    Dim counts As Integer '文書處理範圍計算值
    Dim p As Integer     '計算字元位置的結果值
    
    '計算欄位數目
    Range("A1").Select
    Range(Selection, Selection.End(xlDown)).Select
    counts = Selection.Rows.Count
    MsgBox (counts)
    

    '執行IF條件式迴圈(如果遇到紅色底的儲存格則執行THEN動作
    For i = 1 To counts
    str = Cells(i, 1)
    
    If Cells(i, 1).Interior.Color = RGB(255, 0, 0) Then
     

    '搜尋第三個空白位置
        p = InStrRev(str, " ")
                 

    '刪除多餘位置空白格
            Range("B" & i).Select
            ActiveCell.FormulaR1C1 = "=REPLACE(RC[-1]," & p & ",1,)"
            '複製為純值
            Selection.Copy
            Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
            Range("A" & i).Select
            ActiveSheet.Paste
           

      End If
    Next

End Sub

arrow
arrow

    卡車攝影師 發表在 痞客邦 留言(0) 人氣()