Excel宏:使用宏将字符串与单元格值连接

时间:2016-07-05 04:55:11

标签: string excel vba excel-vba macros

我正在使用Excel 2010。

我有以下宏用于将字符串与单元格值连接起来。

Sub Mac1()
Dim cell As Range
For Each cell In Range("D3", Range("D65536").End(xlUp))
    If cell.Value = "" Then
        cell.Value = ""
    Else
        cell.Value = cell.Value & " Day"
    End If
Next
End Sub

注意:每次运行宏时都会附加字符串Day

预期的结果应该是,如果单元格为空,则没有字符串与单元格连接,如果单元格非空,那么它应该只在一次连接字符串Day和最后的单元格值

1 个答案:

答案 0 :(得分:3)

尝试作为嵌套的If检查字符串是否已在" Day"中结束。

Sub Mac1()
    Dim cell As Range

    With Worksheets("SHeet1")   'KNOW WHAT WORKSHEET YOU ARE ON!!!!!!
        For Each cell In .Range("D3", .Range("D65536").End(xlUp))
            If CBool(Len(cell.Value)) Then
                If Right(LCase(cell.Value), 4) <> " day" Then
                    cell.Value = cell.Value & " Day"
                End If
            End If
        Next cell
    End With
End Sub
相关问题