简体   繁体   English

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

[英]Excel Macro : Concatenate string with cell value using macro

I am using Excel 2010. 我正在使用Excel 2010。

I have the following macro which is used to concatenate the string with cell values. 我有以下宏,用于将字符串与单元格值连接在一起。

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

Note : Getting the string Day appended each and every time when i run the macro. 注意 :每次运行宏时,都将字符串添加为Day

The expected result should be if the cell is empty then no string to be concatenate with the cell, if the cell is non empty then it should concatenate string Day at only one time with the cell value at the end. 预期结果应为:如果该单元格为空,则没有字符串要与该单元格连接;如果该单元格为非空,则它应仅一次连接字符串Day ,单元格值最后。

Try is as a nested If to check if the string already ends in " Day" . 尝试将其作为嵌套的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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