【问题标题】:Remove whitespace in VBA excel删除 VBA excel 中的空格
【发布时间】:2012-05-13 18:03:05
【问题描述】:

我有一些将文本从一个单元格移动到另一个单元格的代码

Dim startIndex As Integer
Dim toIndex As Integer
Dim f As String
Dim g As String

For startIndex = 50 To 60 Step 2
toIndex = Str(startIndex + 1)
f = "F" & Str(toIndex)
g = "G" & Str(startIndex)
Range(f).Value = Range(g).Value
Range(g).Value = ""
Next startIndex

但是变量 f 的值是“F 51”而不是“F51”。

如何解决这个问题? p.s.这是我在 vba 上的第一个代码。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您应该使用
    CStr
    不是
    Str

    那么不需要解决方法来删除不必要的空间

     f = "F" & CStr(toIndex)
     g = "G" & CStr(startIndex)  
    

    来自Str的 Excel 帮助

    将数字转换为字符串时,始终为数字的符号保留前导空格。

    【讨论】:

    • +1 用于解决核心问题。也可以更改为toIndex = startIndex + 1 或使用f = "F" & CStr(startIndex + 1) 取消toIndex
    【解决方案2】:

    您可以在最终结果中使用 TRIM() toIndexREPLACE 空格,即

    Replace ("alphabet", "a", "e")  'would return "elphebet"
    

    从这里提取的示例:http://www.techonthenet.com/excel/formulas/replace.php

    所以...

    f = Replace (f, " ", "")
    

    【讨论】:

    • 对于那些想知道的人,Trim() 只会删除前导和尾随的空白字符,而不是单词之间的空格。
    猜你喜欢
    • 2012-03-11
    • 1970-01-01
    • 2012-03-20
    • 2021-09-23
    • 1970-01-01
    • 2020-03-22
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多