简体   繁体   中英

VBA Excel: Cell value string concatenation does not work

Could you please assist me with the following problem. All I want to do is "clean" a list by adding "0" in front of every cellphone number. This is my code:

Sub ListCleaner_CleanCellPhoneNumbers()
Dim selectedRange As Range
Set selectedRange = getSelectedRange()

Dim i As Integer
Dim max As Integer
i = 1
max = selectedRange.Rows.Count

While i <= max
    Dim cell As Range
    Set cell = selectedRange.Cells(i)

    ' Get row number
    Dim rowNumber As Integer
    rowNumber = cell.Row

    ' Skip header
    If rowNumber > 1 Then
        If Mid(cell.Value, 1, 1) <> "0" Then
            cell.Value = "0" & cell.Value
        End If
    End If

    i = i + 1
Wend

My problem lies in the line 'cell.Value = "0" & cell.Value'. It simply does not add a "0" in front. If I do the following 'cell.Value = "0" & "Hello world"' it works just fine. I also checked and the cell.Value is properly accessed etc.

Any suggestions would be appreciated. Thank you.

UPDATE: I do not think the issue is in the fact that I use a 0 in front. I tried with other numbers as well as characters, all formatted to text etc. Still not working.

If the cell is type of number it will remove all the zeros in the begining. If the cell is typeof text it should work.

I have managed to fix this by using a combinations of the suggested answers. Thanks to @vba4all and @dared for the responses. +1

Here was my solution:

cell.Value = "'0" & LTrim(cell.text)

I had to use a ' before the 0, and use the cell.text instead of the value. The LTrim is used to eliminate leading spaces.

If phone number always has the same length (for example 9 numbers), you can change NumberFormat as states in below code. It will change only numbers, so your headers are safe :)

Sub ListCleaner_CleanCellPhoneNumbers()

Dim selectedRange As Range
Set selectedRange = getSelectedRange()

        selectedRange.NumberFormat = "000000000"

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM