Excel VBA ile Veri Temizleme Otomasyonu

Dağınık bir Excel tablosunu her seferinde elle düzeltmek zaman alır ve aynı kuralları tutarlı uygulamayı zorlaştırır. VBA ile boş satırları kaldırabilir, yinelenen kayıtları kontrol edebilir, metinleri temizleyebilir ve tarih ile tutar biçimlerini tek bir çalıştırılabilir akışta standartlaştırabilirsiniz.

  • Araçlar

Veri temizleme neden otomatikleştirilir?

Excel dosyaları farklı ekiplerden veya sistemlerden geldiğinde boş satırlar, tekrar eden siparişler, başında/sonunda boşluk bulunan metinler ve farklı biçimlerde saklanan tarihler görülebilir. Aynı düzeltmeleri her hafta elle yapmak hem vakit alır hem de hataya açıktır.

Bir VBA makrosu tanımlı kuralları aynı sırayla uygular. Bu örnekte bir satış tablosu üzerinde tamamen boş satırlar silinir, sipariş numarasına göre tekrarlar kaldırılır, müşteri/şehir metinlerindeki görünmeyen ve fazla boşluklar temizlenir, tarih ve tutar alanları biçimlendirilir.

Önemli ayrım: Biçim değiştirmek verinin anlamını değiştirmekle aynı şey değildir. Aşağıdaki makro tarihi ve sayıyı yalnızca güvenle tanıyabildiğinde işler; belirsiz metinleri otomatik tahmin etmek yerine kontrol için sayar.

Örnek dosyayı hazırlama

Makro, çalışma kitabında Veri adlı bir sayfa ve bu sayfada tblVeri adlı bir Excel tablosu olduğunu varsayar. Tablo başlıkları şu adlarla bulunmalı:

BaşlıkKullanımÖrnek
SiparisIDTekil kayıt anahtarı; boş bırakılamazSP-10482
MusteriMetin boşluklarını temizleme“ Deniz Yılmaz ”
SehirMetin boşluklarını temizleme“İzmir ”
SiparisTarihiTarih değerlerini standart görüntüleme12.03.2026
TutarSayısal değerleri aynı ondalık biçimde gösterme2450,5
  1. Veri aralığını seçip Ekle → Tablo ile tabloya dönüştürün; başlık satırı seçili olsun.
  2. Tabloyu seçin, Tablo Tasarımı → Tablo Adı alanına tblVeri yazın.
  3. Sayfa sekmesine sağ tıklayıp Yeniden Adlandır ile sayfaya Veri adını verin.
  4. Dosyayı makro destekli .xlsm biçiminde kaydedin.

Başlık metinleri kodla birebir eşleşmelidir. Kodda farklı adlar kullanacaksanız VBA içindeki ilgili kolon adlarını da değiştirin.

Makronun çalışma sırası

1

Kontrol

Sayfa, tablo, gerekli başlıklar ve anahtar alanı doğrulanır.

2

Boş satırlar

Tüm hücreleri boş olan satırlar tablo içinden sondan başa silinir.

3

Tekrarlar

Aynı SiparisID değerine sahip kayıtlardan ilk görünen korunur.

4

Temizleme

Metin boşlukları ve yazdırılamayan karakterler düzenlenir.

5

Biçim

Tarihler gg.aa.yyyy, sayısal tutarlar iki ondalıkla gösterilir.

6

Özet

Silinen ve değiştirilen kayıt sayıları kullanıcıya bildirilir.

Uçtan uca VBA örneği

Aşağıdaki kodu VBA düzenleyicisinde yeni bir standart modüle ekleyin (Alt+F11 → Ekle → Modül). Makro çalışmadan önce boş olmayan satırlarda SiparisID alanının dolu olmasını şart koşar; eksik anahtar görürse veriyi değiştirmeden durur.

VBA · standart modül
Option Explicit

Public Sub VeriTemizle()
    Dim ws As Worksheet, lo As ListObject
    Dim keyRng As Range, checkRng As Range, c As Range
    Dim i As Long, beforeCount As Long
    Dim blankDeleted As Long, duplicateDeleted As Long
    Dim textChanged As Long, dateReview As Long
    Dim amountReview As Long, missingKeys As Long
    Dim colName As Variant, rawText As String
    Dim cleanText As String, parsedDate As Date
    Dim oldScreen As Boolean, oldEvents As Boolean
    Dim fatalMessage As String, completed As Boolean

    On Error GoTo Hata
    oldScreen = Application.ScreenUpdating
    oldEvents = Application.EnableEvents
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set ws = ThisWorkbook.Worksheets("Veri")
    Set lo = ws.ListObjects("tblVeri")

    If lo.DataBodyRange Is Nothing Then
        completed = True
        GoTo GuvenliCikis
    End If

    ' Gerekli başlık yoksa, aşağıdaki erişim veri değişmeden hata verir.
    Set keyRng = lo.ListColumns("SiparisID").DataBodyRange
    Set checkRng = lo.ListColumns("Musteri").DataBodyRange
    Set checkRng = lo.ListColumns("Sehir").DataBodyRange
    Set checkRng = lo.ListColumns("SiparisTarihi").DataBodyRange
    Set checkRng = lo.ListColumns("Tutar").DataBodyRange

    ' Boş satırları ve eksik anahtarları silme başlamadan say.
    For i = 1 To lo.ListRows.Count
        If Application.WorksheetFunction.CountA(lo.ListRows(i).Range) > 0 Then
            If Len(Trim$(CStr(keyRng.Cells(i, 1).Value2))) = 0 Then
                missingKeys = missingKeys + 1
            End If
        End If
    Next i

    If missingKeys > 0 Then
        fatalMessage = missingKeys & " dolu satırda SiparisID boş. Önce bu kayıtları inceleyin."
        GoTo GuvenliCikis
    End If

    ' Listenin ortasından satır silerken sıra kaymasın diye sondan başa ilerle.
    For i = lo.ListRows.Count To 1 Step -1
        If Application.WorksheetFunction.CountA(lo.ListRows(i).Range) = 0 Then
            lo.ListRows(i).Delete
            blankDeleted = blankDeleted + 1
        End If
    Next i

    If lo.DataBodyRange Is Nothing Then
        completed = True
        GoTo GuvenliCikis
    End If

    ' RemoveDuplicates sütun numarası tablo aralığına göredir; başlık satırı vardır.
    beforeCount = lo.ListRows.Count
    lo.Range.RemoveDuplicates _
        Columns:=Array(lo.ListColumns("SiparisID").Index), _
        Header:=xlYes
    duplicateDeleted = beforeCount - lo.ListRows.Count

    ' Görünmeyen ASCII karakterlerini, NBSP'yi ve fazla boşlukları temizle.
    For Each colName In Array("Musteri", "Sehir")
        For Each c In lo.ListColumns(CStr(colName)).DataBodyRange.Cells
            If Not IsError(c.Value2) Then
                rawText = CStr(c.Value2)
                cleanText = Application.WorksheetFunction.Clean(rawText)
                cleanText = Replace(cleanText, ChrW(160), " ")
                cleanText = Application.WorksheetFunction.Trim(cleanText)
                If cleanText <> rawText Then
                    c.Value = cleanText
                    textChanged = textChanged + 1
                End If
            End If
        Next c
    Next colName

    ' Gerçek Excel tarihini veya açıkça ISO biçimindeki yyyy-aa-gg metnini kabul et.
    For Each c In lo.ListColumns("SiparisTarihi").DataBodyRange.Cells
        If Not IsError(c.Value2) Then
            If Len(Trim$(CStr(c.Value2))) > 0 Then
                If VarType(c.Value) = vbDate Then
                    c.NumberFormat = "dd.mm.yyyy"
                ElseIf TryParseISODate(CStr(c.Value2), parsedDate) Then
                    c.Value = parsedDate
                    c.NumberFormat = "dd.mm.yyyy"
                Else
                    dateReview = dateReview + 1
                End If
            End If
        End If
    Next c

    ' Sayısal tutarı biçimlendir; metin değerini bölgesel ayar tahminiyle dönüştürme.
    For Each c In lo.ListColumns("Tutar").DataBodyRange.Cells
        If Not IsError(c.Value2) Then
            If Len(Trim$(CStr(c.Value2))) > 0 Then
                If IsNumeric(c.Value2) And VarType(c.Value2) <> vbString Then
                    c.NumberFormat = "#,##0.00"
                Else
                    amountReview = amountReview + 1
                End If
            End If
        End If
    Next c

    completed = True

GuvenliCikis:
    On Error Resume Next
    Application.ScreenUpdating = oldScreen
    Application.EnableEvents = oldEvents
    On Error GoTo 0

    If Len(fatalMessage) > 0 Then
        MsgBox fatalMessage, vbExclamation, "Veri temizleme durduruldu"
    ElseIf completed Then
        MsgBox "Temizleme tamamlandı." & vbCrLf & _
            "Silinen boş satır: " & blankDeleted & vbCrLf & _
            "Kaldırılan yinelenen kayıt: " & duplicateDeleted & vbCrLf & _
            "Düzenlenen metin hücresi: " & textChanged & vbCrLf & _
            "İncelenecek tarih / tutar: " & dateReview & " / " & amountReview, _
            vbInformation, "Veri temizleme"
    End If
    Exit Sub

Hata:
    fatalMessage = "Makro çalışırken hata oluştu: " & Err.Description
    Resume GuvenliCikis
End Sub

Private Function TryParseISODate( _
    ByVal valueText As String, ByRef parsed As Date) As Boolean
    Dim parts() As String
    On Error GoTo Gecersiz

    valueText = Trim$(valueText)
    parts = Split(valueText, "-")
    If UBound(parts) <> 2 Then Exit Function
    If Len(parts(0)) <> 4 Or _
       Len(parts(1)) <> 2 Or _
       Len(parts(2)) <> 2 Then Exit Function
    If Not IsNumeric(parts(0)) Or _
       Not IsNumeric(parts(1)) Or _
       Not IsNumeric(parts(2)) Then Exit Function

    parsed = DateSerial(CInt(parts(0)), CInt(parts(1)), CInt(parts(2)))
    ' DateSerial geçersiz günleri sonraki aya taşıyabilir; geri biçimleyerek doğrula.
    If Format$(parsed, "yyyy-mm-dd") = valueText Then
        TryParseISODate = True
    End If
    Exit Function

Gecersiz:
    TryParseISODate = False
End Function
Kod bloğu: Sayfada gördüğünüz operatörler kopyalandığında VBA için doğru karakterler olarak aktarılır; yalnızca HTML kaynak kodundaki gösterim farklıdır.

Kodun önemli parçaları

Boş satırları sondan başa silme

Satırlar tablodan kaldırıldıkça alttaki satırların indeksleri değişir. Döngüyü son satırdan ilk satıra doğru çalıştırmak, henüz incelenmemiş satırların atlanmasını önler. CountA satırdaki dolu hücreleri sayar; tüm tablo satırı boşsa o satır silinir.

Yinelenen kayıt ölçütünü açık seçme

RemoveDuplicates çağrısında yalnızca SiparisID sütunu kullanılır. Bu nedenle aynı sipariş kimliğine sahip satırlardan ilk görünen kalır. İlk satırın en güncel kayıt olduğuna dair garanti yoksa çalıştırmadan önce sıralama yapın veya hangi kaydın korunacağını belirleyen ayrı bir kural ekleyin. Microsoft VBA belgesi Columns parametresini yinelenenliği belirleyen sütun indeksleri dizisi, Header parametresini başlık satırı seçimi olarak tanımlar.

Metni düzenleme

Clean yazdırılamayan bazı ASCII karakterlerini kaldırır. ChrW(160) ile web ve dışa aktarımlarda görülebilen bölünemez boşluk sıradan boşluğa çevrilir; Excel’in Trim fonksiyonu baştaki/sondaki boşlukları temizler ve kelimeler arasındaki tekrarları tek boşluğa indirir. Kod ad/şehir yazımını otomatik olarak büyük/küçük harfe çevirmediğinden marka ve kişi adlarının biçimi korunur.

Tarih ve tutar alanları

Makro gerçek Excel tarihlerini biçimlendirir ve yalnızca açık ISO yyyy-aa-gg metnini tarih olarak yorumlar. Örneğin 03/04/2026 yerel ayara göre farklı okunabileceği için otomatik çevrilmez, inceleme sayısına eklenir. Tutar sütununda yalnızca sayısal hücreye sayı biçimi uygulanır; metin olarak gelen para değerleri binlik/ondalık ayıracı tahmin edilmeden incelenmek üzere bırakılır. Excel’de sayı biçimi, değerin nasıl gösterileceğini belirler; sayı metnini para birimine dönüştürmez.

Kimlikleri metin tutun: 00047 gibi baştaki sıfırlar önemliyse veriyi içeri aktarırken sütunu Metin olarak belirleyin. Sayı olarak içe aktarıldıktan sonra baştaki sıfırlar kaybolmuş olabilir; biçim kodu bunları kendiliğinden geri getirmez.

Makroyu ekleme ve çalıştırma

  1. Dosyanın bir yedeğini alın; makro satır silebilir ve yinelenen kayıtları kaldırır.
  2. Alt+F11 ile Visual Basic for Applications düzenleyicisini açın.
  3. Ekle → Modül seçin ve makro ile yardımcı fonksiyonu aynı standart modüle yapıştırın.
  4. VBA kodunu eklerken HTML kod bloğunda kaçışlanmış operatörleri gerçek karakterleriyle kullanın; örneğin &amp; yazan görünen yer VBA’da & olur.
  5. Dosyayı .xlsm olarak kaydedin. Excel’e dönüp Geliştirici → Makrolar → VeriTemizle → Çalıştır yolunu izleyin.
  6. Özet penceresindeki sayıları ve inceleme gerektiren tarih/tutar hücrelerini kaynak dosyayla karşılaştırın.

Geliştirici sekmesi görünmüyorsa Excel seçeneklerinden Şeridi Özelleştir bölümüne gidip Geliştirici kutusunu etkinleştirin. Güvenlik ayarlarında yalnızca güvendiğiniz dosyalardaki makrolara izin verin.

Gerçek dosyanıza uyarlama

İhtiyaçUyarlamaKontrol
Tekrarı birkaç alan birlikte belirlesinColumns:=Array(...) içine örneğin sipariş no ve ürün kodu indekslerini ekleyin.Kolon indeksleri tablo aralığına göredir; başlık aralığının dışındaki sayfa sütun numaraları değildir.
Boş satır yerine eksik alanlı kayıtları bulmaGerekli kolonlarda boş değer kontrolü yapıp silmek yerine ayrı raporlayın.Eksik değer her zaman hatalı kayıt demek değildir; iş kuralını doğrulayın.
Başka metin alanlarını temizlemeArray("Musteri", "Sehir") listesine başlıkları ekleyin.Kodları, ürün adlarını ve e-posta adreslerini otomatik büyük harfe çevirmeyin; alanın anlamını göz önüne alın.
Para birimi göstermekYerel dosya standardına uygun bir sayı biçimi uygulayın.Sadece görüntü biçimi değişir; döviz çevrimi için kur tablosu ve tarih kuralı gerekir.

Excel VBA’nın Range.RemoveDuplicates yöntemi yinelenenleri belirli sütun indekslerine göre kaldırır. WorksheetFunction.Clean yazdırılamayan ASCII karakterlerin bir bölümünü temizler; WorksheetFunction.Trim kelimeler arasındaki fazla sıradan boşlukları teke indirir. VBA tablosundaki veri satırları ListObject.ListRows koleksiyonu üzerinden ele alınır.

Çalıştırma öncesi kontrol listesi

  • Orijinal dosyanın yedeği var mı?
  • Sayfa ve tablo adları kodla aynı mı?
  • Gerekli kolon başlıkları birebir eşleşiyor mu?
  • Yinelenen kayıt ölçütü yalnızca SiparisID mi, yoksa birden çok alan mı?
  • Aynı kimlikten birden fazla kayıt varsa hangisinin kalması gerekiyor?
  • Tarih ve tutar sütunlarında metin olarak saklanan değerler ayrıca incelenecek mi?
  • Makro özeti ve örnek satırlar kaynak dosyayla karşılaştırıldı mı?
İyi uygulama: İlk çalıştırmayı dosyanın kopyasında yapın. Temizleme kuralı onaylandıktan sonra makroyu düğmeye bağlayabilir ve her çalışmada işlem tarihini, dosya adını ve sonuç sayaçlarını bir günlük sayfasına yazdırabilirsiniz.

Özet

VBA, tekrarlanan veri temizleme adımlarını çalıştırılabilir bir sürece dönüştürür. Bu örnek tamamen boş tablo satırlarını siler, dolu satırlarda anahtar alanı kontrol eder, sipariş numarasına göre tekrarları kaldırır, metindeki fazla/görünmeyen boşlukları temizler ve güvenle tanıyabildiği tarih ile tutarları biçimlendirir. Belirsiz değerleri sessizce dönüştürmek yerine raporlaması, otomasyonun denetlenebilir kalmasına yardımcı olur.

Kaynaklar

Why automate data cleaning?

When Excel files arrive from different teams or systems, you tend to see empty rows, repeated orders, text with leading or trailing spaces, and dates stored in several different formats. Making the same corrections by hand every week takes time and invites mistakes.

A VBA macro applies defined rules in the same order every time. In this example, working on a sales table, entirely empty rows are deleted, duplicates are removed by order number, invisible and excess spaces are cleaned out of the customer and city text, and the date and amount fields are formatted.

An important distinction: changing a format is not the same as changing the meaning of the data. The macro below touches a date or a number only when it can recognise it safely; rather than guessing at ambiguous text, it counts those cells for review.

Preparing the example file

The macro assumes the workbook has a sheet named Data containing an Excel table named tblData. The table headers must carry these names:

HeaderUsed forExample
OrderIDThe unique record key; cannot be left emptySP-10482
CustomerCleaning text whitespace" Deniz Yılmaz "
CityCleaning text whitespace"İzmir "
OrderDateDisplaying date values consistently12.03.2026
AmountShowing numeric values with the same decimals2450.5
  1. Select the data range and turn it into a table with Insert → Table, with the header row ticked.
  2. Select the table and type tblData into Table Design → Table Name.
  3. Right-click the sheet tab, choose Rename and name the sheet Data.
  4. Save the file in the macro-enabled .xlsm format.

The header text has to match the code exactly. If you want to use different names, change the corresponding column names inside the VBA as well.

The order the macro runs in

1

Checks

The sheet, the table, the required headers and the key field are verified.

2

Empty rows

Rows whose cells are all empty are deleted from the table, bottom to top.

3

Duplicates

Among records sharing an OrderID, the first one encountered is kept.

4

Cleaning

Text whitespace and non-printing characters are tidied up.

5

Format

Dates are shown as dd.mm.yyyy and numeric amounts with two decimals.

6

Summary

The number of deleted and modified records is reported to the user.

An end-to-end VBA example

Add the code below to a new standard module in the VBA editor (Alt+F11 → Insert → Module). Before it runs, the macro requires the OrderID field to be filled on every non-empty row; if it finds a missing key it stops without changing the data.

VBA · standard module
Option Explicit

Public Sub CleanData()
    Dim ws As Worksheet, lo As ListObject
    Dim keyRng As Range, checkRng As Range, c As Range
    Dim i As Long, beforeCount As Long
    Dim blankDeleted As Long, duplicateDeleted As Long
    Dim textChanged As Long, dateReview As Long
    Dim amountReview As Long, missingKeys As Long
    Dim colName As Variant, rawText As String
    Dim cleanText As String, parsedDate As Date
    Dim oldScreen As Boolean, oldEvents As Boolean
    Dim fatalMessage As String, completed As Boolean

    On Error GoTo Failure
    oldScreen = Application.ScreenUpdating
    oldEvents = Application.EnableEvents
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Set ws = ThisWorkbook.Worksheets("Data")
    Set lo = ws.ListObjects("tblData")

    If lo.DataBodyRange Is Nothing Then
        completed = True
        GoTo SafeExit
    End If

    ' If a required header is missing, the access below errors without touching the data.
    Set keyRng = lo.ListColumns("OrderID").DataBodyRange
    Set checkRng = lo.ListColumns("Customer").DataBodyRange
    Set checkRng = lo.ListColumns("City").DataBodyRange
    Set checkRng = lo.ListColumns("OrderDate").DataBodyRange
    Set checkRng = lo.ListColumns("Amount").DataBodyRange

    ' Count empty rows and missing keys before any deletion begins.
    For i = 1 To lo.ListRows.Count
        If Application.WorksheetFunction.CountA(lo.ListRows(i).Range) > 0 Then
            If Len(Trim$(CStr(keyRng.Cells(i, 1).Value2))) = 0 Then
                missingKeys = missingKeys + 1
            End If
        End If
    Next i

    If missingKeys > 0 Then
        fatalMessage = missingKeys & " non-empty rows have no OrderID. Review those records first."
        GoTo SafeExit
    End If

    ' Walk from the bottom up so deleting mid-list rows does not shift the indexes.
    For i = lo.ListRows.Count To 1 Step -1
        If Application.WorksheetFunction.CountA(lo.ListRows(i).Range) = 0 Then
            lo.ListRows(i).Delete
            blankDeleted = blankDeleted + 1
        End If
    Next i

    If lo.DataBodyRange Is Nothing Then
        completed = True
        GoTo SafeExit
    End If

    ' RemoveDuplicates column numbers are relative to the table range, which has a header row.
    beforeCount = lo.ListRows.Count
    lo.Range.RemoveDuplicates _
        Columns:=Array(lo.ListColumns("OrderID").Index), _
        Header:=xlYes
    duplicateDeleted = beforeCount - lo.ListRows.Count

    ' Clear non-printing ASCII characters, NBSP and excess spaces.
    For Each colName In Array("Customer", "City")
        For Each c In lo.ListColumns(CStr(colName)).DataBodyRange.Cells
            If Not IsError(c.Value2) Then
                rawText = CStr(c.Value2)
                cleanText = Application.WorksheetFunction.Clean(rawText)
                cleanText = Replace(cleanText, ChrW(160), " ")
                cleanText = Application.WorksheetFunction.Trim(cleanText)
                If cleanText <> rawText Then
                    c.Value = cleanText
                    textChanged = textChanged + 1
                End If
            End If
        Next c
    Next colName

    ' Accept a real Excel date, or text that is explicitly in ISO yyyy-mm-dd form.
    For Each c In lo.ListColumns("OrderDate").DataBodyRange.Cells
        If Not IsError(c.Value2) Then
            If Len(Trim$(CStr(c.Value2))) > 0 Then
                If VarType(c.Value) = vbDate Then
                    c.NumberFormat = "dd.mm.yyyy"
                ElseIf TryParseISODate(CStr(c.Value2), parsedDate) Then
                    c.Value = parsedDate
                    c.NumberFormat = "dd.mm.yyyy"
                Else
                    dateReview = dateReview + 1
                End If
            End If
        End If
    Next c

    ' Format numeric amounts; do not convert text values by guessing the locale.
    For Each c In lo.ListColumns("Amount").DataBodyRange.Cells
        If Not IsError(c.Value2) Then
            If Len(Trim$(CStr(c.Value2))) > 0 Then
                If IsNumeric(c.Value2) And VarType(c.Value2) <> vbString Then
                    c.NumberFormat = "#,##0.00"
                Else
                    amountReview = amountReview + 1
                End If
            End If
        End If
    Next c

    completed = True

SafeExit:
    On Error Resume Next
    Application.ScreenUpdating = oldScreen
    Application.EnableEvents = oldEvents
    On Error GoTo 0

    If Len(fatalMessage) > 0 Then
        MsgBox fatalMessage, vbExclamation, "Data cleaning stopped"
    ElseIf completed Then
        MsgBox "Cleaning finished." & vbCrLf & _
            "Empty rows deleted: " & blankDeleted & vbCrLf & _
            "Duplicate records removed: " & duplicateDeleted & vbCrLf & _
            "Text cells modified: " & textChanged & vbCrLf & _
            "Dates / amounts to review: " & dateReview & " / " & amountReview, _
            vbInformation, "Data cleaning"
    End If
    Exit Sub

Failure:
    fatalMessage = "An error occurred while the macro was running: " & Err.Description
    Resume SafeExit
End Sub

Private Function TryParseISODate( _
    ByVal valueText As String, ByRef parsed As Date) As Boolean
    Dim parts() As String
    On Error GoTo Invalid

    valueText = Trim$(valueText)
    parts = Split(valueText, "-")
    If UBound(parts) <> 2 Then Exit Function
    If Len(parts(0)) <> 4 Or _
       Len(parts(1)) <> 2 Or _
       Len(parts(2)) <> 2 Then Exit Function
    If Not IsNumeric(parts(0)) Or _
       Not IsNumeric(parts(1)) Or _
       Not IsNumeric(parts(2)) Then Exit Function

    parsed = DateSerial(CInt(parts(0)), CInt(parts(1)), CInt(parts(2)))
    ' DateSerial can roll an invalid day into the next month; verify by formatting back.
    If Format$(parsed, "yyyy-mm-dd") = valueText Then
        TryParseISODate = True
    End If
    Exit Function

Invalid:
    TryParseISODate = False
End Function
About the code block: the operators you see on the page transfer as the correct characters for VBA when you copy them; only the representation in the HTML source differs.

The important pieces of the code

Deleting empty rows from the bottom up

As rows are removed from the table, the indexes of the rows beneath them change. Running the loop from the last row to the first prevents rows you have not examined yet from being skipped. CountA counts the filled cells in a row; if the whole table row is empty, that row is deleted.

Choosing the duplicate criterion explicitly

The RemoveDuplicates call uses only the OrderID column, so among rows sharing an order identifier the first one encountered stays. If you have no guarantee that the first row is the most recent record, sort before running or add a separate rule that decides which record to keep. Microsoft's VBA documentation defines the Columns parameter as the array of column indexes that determine duplication, and Header as the header row setting.

Tidying up text

Clean removes some non-printing ASCII characters. ChrW(160) converts the non-breaking space you often see in web content and exports into an ordinary space; Excel's Trim function clears leading and trailing spaces and reduces repeats between words to a single space. Because the code does not change the capitalisation of names or cities automatically, the formatting of brand and personal names is preserved.

The date and amount fields

The macro formats genuine Excel dates and interprets only explicit ISO yyyy-mm-dd text as a date. A value such as 03/04/2026 can be read differently depending on the locale, so it is not converted automatically; it is added to the review count. In the amount column, a number format is applied only to numeric cells; currency values that arrive as text are left for review rather than having their thousands and decimal separators guessed. In Excel, a number format determines how a value is displayed; it does not turn numeric text into a currency value.

Keep identifiers as text: if leading zeros such as 00047 matter, set the column type to Text while importing the data. Once it has been imported as a number the leading zeros may already be gone, and a format code will not bring them back on its own.

Adding and running the macro

  1. Take a backup of the file; the macro can delete rows and it removes duplicate records.
  2. Open the Visual Basic for Applications editor with Alt+F11.
  3. Choose Insert → Module and paste the macro and the helper function into the same standard module.
  4. When you add the VBA code, use the real characters in place of the operators escaped in the HTML code block; where you see &amp;, for instance, VBA needs &.
  5. Save the file as .xlsm. Back in Excel, follow Developer → Macros → CleanData → Run.
  6. Compare the counts in the summary window, and the date and amount cells flagged for review, against the source file.

If the Developer tab is not visible, go to Customize Ribbon in the Excel options and tick the Developer box. In your security settings, allow macros only in files you trust.

Adapting it to your own file

What you needHow to adapt itWhat to check
Duplication decided by several fields togetherAdd the indexes of, say, the order number and the product code inside Columns:=Array(...).Column indexes are relative to the table range, not the sheet column numbers outside the header range.
Finding records with missing fields rather than empty rowsCheck the required columns for empty values and report them separately instead of deleting.A missing value does not always mean a faulty record; confirm the business rule.
Cleaning other text fieldsAdd the headers to the Array("Customer", "City") list.Do not auto-uppercase codes, product names or e-mail addresses; consider what the field means.
Displaying a currencyApply a number format that suits the file's local standard.Only the display format changes; converting currency needs an exchange rate table and a date rule.

Excel VBA's Range.RemoveDuplicates method removes duplicates according to specific column indexes. WorksheetFunction.Clean clears a subset of non-printing ASCII characters, and WorksheetFunction.Trim reduces excess ordinary spaces between words to one. The data rows of a VBA table are handled through the ListObject.ListRows collection.

A checklist before you run it

  • Is there a backup of the original file?
  • Do the sheet and table names match the code?
  • Do the required column headers match exactly?
  • Is the duplicate criterion OrderID alone, or several fields?
  • If there is more than one record with the same identifier, which one should stay?
  • Will values stored as text in the date and amount columns be reviewed separately?
  • Have the macro summary and a sample of rows been compared against the source file?
Good practice: do the first run on a copy of the file. Once the cleaning rule is confirmed you can attach the macro to a button and have each run write the date, the file name and the result counters to a log sheet.

Summary

VBA turns repeated data cleaning steps into an executable process. This example deletes entirely empty table rows, checks the key field on the filled ones, removes duplicates by order number, clears excess and invisible whitespace from text, and formats the dates and amounts it can recognise safely. Reporting ambiguous values instead of converting them silently is what keeps the automation auditable.

Resources