【问题标题】:VBA excel extra spaces in concatenation [duplicate]VBA excel连接中的额外空格[重复]
【发布时间】:2021-02-27 01:38:01
【问题描述】:

我有一个 VBA 代码,我必须在其中循环某个范围并使用一些连接来填充它,但我的 VBA 代码添加了不需要的空格。例如,让我们假设以下示例:

code = "NV"
ac = "Curncy"

With wsNew

Set rng = .Range(Cells(2, 2), Cells(2, 2).End(xlDown))

For Each r In rng
    
    If r.Value = 17 Or r.Value = 18 Or r.Value = 19 Then
        
        r.Offset(, 1) = code + r.Offset(, -1).Value + Str(Right(r.Value, 1)) + " " + Str(r.Value) + _
        " " + ac
    
    Else
    
        r.Offset(, 1) = code + r.Offset(, -1).Value + Str(Right(r.Value, 1)) + _
        " " + ac
    
    End If

Next r

End With

对于第一个单元格(示例中的r 变量),我有r.Value = 18r.offset(,-1).Value = U,我希望为我的r.Offset(, 1) 获得NVU8 18 Curncy 的值。相反,代码添加了空格,我得到NVU 8 18 Curncy,在 U 和 8 之间有一个空格(要删除),在 8 和 18 之间有两个空格,而不是只有一个。

【问题讨论】:

  • 使用 Cstr 而不是 Str。也可以将 & 用于连接,而不是 +。

标签: excel vba concatenation


【解决方案1】:

来自Str 文档:

将数字转换为字符串时,始终为数字的符号保留前导空格。如果 number 为正数,则返回的字符串包含前导空格并隐含加号。

不要使用Str,而是使用& 来连接,而不是+& 强制两个表达式的字符串连接。

r.Offset(, 1).Value = code & r.Offset(, -1).Value & Right(r.Value, 1) & " " & r.Value & _
        " " & ac

【讨论】:

  • 有趣的 Str 笔记 - 谢谢!效果很好。理解为 & 而不是 +
【解决方案2】:

BigBen 给出了解决方案

这是您的代码的可能增强(参见 cmets)

With wsNew

    Set Rng = .Range(.Cells(2, 2), .Cells(2, 2).End(xlDown)) ' <-- use dots (".") before all range references !
    
    For Each r In Rng
        
        Select Case r.Value2 ' <-- "Select Case" syntax  can make it more readable and maintanable then a multiple If Then Else
            Case 17, 18, 19
            
                r.Offset(, 1).Value2 = code & r.Offset(, -1).Value2 & Right$(r.Value2, 1) & " " & r.Value2 & " " & ac
        
            Case Else
        
                r.Offset(, 1).Value2 = code & r.Offset(, -1).Value2 & Right$(r.Value2, 1) & " " & ac
        
        End If
    
    Next

End With

使用Value2 属性可以消除可能不需要的部分(请参阅this answer

【讨论】:

  • 感谢点建议...我忘记了 VBA 中的 Select Case 语句,请注意!
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多