Some Useful Excel Macros

Replace Line in a text file

Sub OpenEditSaveCloseTextFile()
    Dim fso As Object
    Dim fil As Object
    Dim txt As Object
    Dim str_path As String
    Dim str_change As String

    str_path = "e:\test"
    Set fso = CreateObject("Scripting.FileSystemObject")
    MsgBox ("Starting Replacement")
    For Each fil In fso.GetFolder(str_path).Files
        'If fil.Type = "Text Document" Then
            Set txt = fil.OpenAsTextStream(1)
            str_change = txt.ReadAll
            txt.Close
            str_change = Replace(str_change, "FIND_WHAT", "REPLACE_WITH", , , vbTextCompare)
            With fil.OpenAsTextStream(2)
                .Write str_change
                .Close
            End With
        'End If
    Next fil
    MsgBox ("Replacement Completed")
End Sub

#Remove beginning “-“ from the cell content

Sub Test()
For Each cell In ActiveSheet.UsedRange
On Error Resume Next
    If Left(cell.Formula, 2) = "=-" Then
            cell.Formula = "'" & Mid(cell.Formula, 2, Len(cell.Formula) - 1)
    End If
Next
End Sub


#Remove duplicates in a cell
Sub remDup()
Dim dic As Object, cell As Range, temp As Variant
Dim i As Long
Set dic = CreateObject("scripting.dictionary")
With dic
    For Each cell In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row)
        .removeall
        If Len(cell.Value) > 0 Then
            temp = Split(" " & cell.Value, ",")
            For i = 0 To UBound(temp)
                If Not .Exists(temp(i)) Then .Add temp(i), temp(i)
            Next i
            cell.Value = Mid(Join(.Keys, ","),2)
        End If
    Next cell
End With
       
End Sub

Reverse String (in a new module)


Option Explicit

Public Function ReverseString(Text As String)
    
    ReverseString = StrReverse(Text)
    
End Function

Popular posts from this blog

How To Unlock Bootloaders on your Xperia Arc S

Inherited Colour Vision Deficiency