# Excel VBA ile Veri Temizleme Otomasyonu

> Excel VBA ile boş satır silme, yinelenen kayıtları belirleme, metin temizleme ve tarih/tutar biçimlerini standartlaştırma rehberi.

Kaynak: https://ozgurnurettinozturk.com/excel-vba-ile-veri-temizleme-otomasyonu | Bu sayfanin HTML surumu ayni adrestedir ve Ingilizce cevirisini de icerir.

---
# 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

## İçindekiler

- [Neden otomatikleştirmeli?](#neden)

- [Örnek dosyayı hazırla](#hazirlik)

- [Makro adımları](#akis)

- [Uçtan uca VBA kodu](#kod)

- [Kodun parçaları](#adimlar)

- [Kurulum ve çalıştırma](#uygulama)

- [Dosyana uyarlama](#uyarlama)

- [Kontrol listesi](#kontrol)

- [Özet](#ozet)

- [Kaynaklar](#kaynak)

## 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.

## Ö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ık | Kullanım | Örnek |
|---|---|---|
| `SiparisID` | Tekil kayıt anahtarı; boş bırakılamaz | SP-10482 |
| `Musteri` | Metin boşluklarını temizleme | “ Deniz Yılmaz ” |
| `Sehir` | Metin boşluklarını temizleme | “İzmir ” |
| `SiparisTarihi` | Tarih değerlerini standart görüntüleme | 12.03.2026 |
| `Tutar` | Sayısal değerleri aynı ondalık biçimde gösterme | 2450,5 |

- Veri aralığını seçip **Ekle → Tablo** ile tabloya dönüştürün; başlık satırı seçili olsun.

- Tabloyu seçin, **Tablo Tasarımı → Tablo Adı** alanına `tblVeri` yazın.

- Sayfa sekmesine sağ tıklayıp **Yeniden Adlandır** ile sayfaya `Veri` adını verin.

- 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ı

### Kontrol

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

### Boş satırlar

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

### Tekrarlar

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

### Temizleme

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

### Biçim

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

### Ö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*

```vb
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
```

## 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.

## Makroyu ekleme ve çalıştırma

- Dosyanın bir yedeğini alın; makro satır silebilir ve yinelenen kayıtları kaldırır.

- **Alt+F11** ile Visual Basic for Applications düzenleyicisini açın.

- **Ekle → Modül** seçin ve makro ile yardımcı fonksiyonu aynı standart modüle yapıştırın.

- VBA kodunu eklerken HTML kod bloğunda kaçışlanmış operatörleri gerçek karakterleriyle kullanın; örneğin `&` yazan görünen yer VBA’da `&` olur.

- Dosyayı `.xlsm` olarak kaydedin. Excel’e dönüp **Geliştirici → Makrolar → VeriTemizle → Çalıştır** yolunu izleyin.

- Ö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ç | Uyarlama | Kontrol |
|---|---|---|
| Tekrarı birkaç alan birlikte belirlesin | `Columns:=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ı bulma | Gerekli 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ı temizleme | `Array("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östermek | Yerel 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](https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates) yöntemi yinelenenleri belirli sütun indekslerine göre kaldırır. [WorksheetFunction.Clean](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.clean) yazdırılamayan ASCII karakterlerin bir bölümünü temizler; [WorksheetFunction.Trim](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.trim) kelimeler arasındaki fazla sıradan boşlukları teke indirir. VBA tablosundaki veri satırları [ListObject.ListRows](https://learn.microsoft.com/en-us/office/vba/api/excel.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ı?

## Ö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

- [Microsoft Learn — Range.RemoveDuplicates](https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates)

- [Microsoft Learn — WorksheetFunction.Clean](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.clean)

- [Microsoft Learn — WorksheetFunction.Trim](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.trim)

- [Microsoft Learn — ListObject.ListRows](https://learn.microsoft.com/en-us/office/vba/api/excel.listobject.listrows)

## 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:

| Header | Used for | Example |
|---|---|---|
| `OrderID` | The unique record key; cannot be left empty | SP-10482 |
| `Customer` | Cleaning text whitespace | " Deniz Yılmaz " |
| `City` | Cleaning text whitespace | "İzmir " |
| `OrderDate` | Displaying date values consistently | 12.03.2026 |
| `Amount` | Showing numeric values with the same decimals | 2450.5 |

- Select the data range and turn it into a table with **Insert → Table**, with the header row ticked.

- Select the table and type `tblData` into **Table Design → Table Name**.

- Right-click the sheet tab, choose **Rename** and name the sheet `Data`.

- 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

### Checks

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

### Empty rows

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

### Duplicates

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

### Cleaning

Text whitespace and non-printing characters are tidied up.

### Format

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

### 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*

```vb
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
```

## 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.

## Adding and running the macro

- Take a backup of the file; the macro can delete rows and it removes duplicate records.

- Open the Visual Basic for Applications editor with **Alt+F11**.

- Choose **Insert → Module** and paste the macro and the helper function into the same standard module.

- When you add the VBA code, use the real characters in place of the operators escaped in the HTML code block; where you see `&`, for instance, VBA needs `&`.

- Save the file as `.xlsm`. Back in Excel, follow **Developer → Macros → CleanData → Run**.

- 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 need | How to adapt it | What to check |
|---|---|---|
| Duplication decided by several fields together | Add 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 rows | Check 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 fields | Add 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 currency | Apply 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](https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates) method removes duplicates according to specific column indexes. [WorksheetFunction.Clean](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.clean) clears a subset of non-printing ASCII characters, and [WorksheetFunction.Trim](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.trim) reduces excess ordinary spaces between words to one. The data rows of a VBA table are handled through the [ListObject.ListRows](https://learn.microsoft.com/en-us/office/vba/api/excel.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?

## 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

- [Microsoft Learn — Range.RemoveDuplicates](https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates)

- [Microsoft Learn — WorksheetFunction.Clean](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.clean)

- [Microsoft Learn — WorksheetFunction.Trim](https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.trim)

- [Microsoft Learn — ListObject.ListRows](https://learn.microsoft.com/en-us/office/vba/api/excel.listobject.listrows)

## Diğer Yazılar

### Excel VBA ile Raporlama Otomasyonu

### Excel VBA ile Pivot Table Otomasyonu

### Power Query Nedir? Excel ve Power BI ile Veri Dönüştürme
