0

I have a table in excel that I'm eventually going to read into a sql database. I have \"@\" as a custom code to wrap the text with quotes. However, I also tried to replace all the blank values with NULL, but those also get quotes wrapped around them.

Is there a custom code I can use that'll wrap every string except NULL in text?

JesusMonroe
  • 1,421
  • 3
  • 13
  • 20

1 Answers1

1

After a bunch of research (1, 2, 3, 4, 5), and finding myself impressed at how many features that custom number formats actually has, it appears to me that number formats can't do what you're looking for.

It can't compare the actual value of a cell against a given value (like "NULL"); it can only be used to discern between the type of value stored in a cell, whether it's one of these: POSITIVE; NEGATIVE; ZERO; TEXT.

With that in mind, you could do this pretty easily with a VBA solution. Since I'm guessing a bit at your situation, here are some options.

This first option will not automatically change the number format of your cells, but if you don't mind 'manually' updating the number formats, you could run this macro below to force it to update the number formats.

Option Explicit

Sub NumberFormatting()

    Dim rng As Range
    Set rng = Range("A1:B4")    'adjust range as necessary

    Dim cel As Range
    For Each cel In rng.Cells
        If cel.Value2 = "NULL" Then
            cel.NumberFormat = "@"
        Else
            cel.NumberFormat = "\""@\"""
        End If
    Next cel

End Sub

If you wanted the number formatting to change automatically, you can drop this code into the sheet's module and any time you update a cell within the specified range it will check whether that new value is "NULL" and update the number format when that is the case.

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rng As Range
    Set rng = Range("A1:B4")    'adjust range as necessary

    If Not Intersect(Target, rng) Is Nothing Then
        If Target.Value2 = "NULL" Then
            Target.NumberFormat = "@"
        Else
            Target.NumberFormat = "\""@\"""
        End If
    End If

End Sub
Marcucciboy2
  • 3,156
  • 3
  • 20
  • 38