删除VBA excel中的空格

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

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 

但variablesf具有“F 51”值而不是“F51”。

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

你可以TRIM() toIndexREPLACE空格在最后的结果,即

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

例子从这里解除: http : //www.techonthenet.com/excel/formulas/replace.php

所以…

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

你应该使用
CStr

Str

然后,没有解决方法是需要删除一个无生命的空间

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

从Excel帮助Str

将数字转换为string时,总是为数字的符号预留前导空格。