删除VBA excel中的空格

BIL*_*ILL 3 excel vba

我有一些代码用于将文本从单元格移动到单元格

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
Run Code Online (Sandbox Code Playgroud)

但变量f具有"F 51"值而不是"F51".

怎么解决这个问题?ps这是我在vba上的第一个代码.

bre*_*tdj 14

你应该用
CStr

Str

然后,不需要解决方法来移除不必要的空间

 f = "F" & CStr(toIndex)
 g = "G" & CStr(startIndex)  
Run Code Online (Sandbox Code Playgroud)

从Excel帮助 Str

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

  • 获得核心问题的+1.也可以改为`toIndex = startIndex + 1`或者使用`f ="F"&CStr(startIndex + 1)取消`toIndex` (2认同)

Mar*_*arc 8

你可以在最终结果中TRIM()使用toIndex或者REPLACE空格,即

Replace ("alphabet", "a", "e")  'would return "elphebet"
Run Code Online (Sandbox Code Playgroud)

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

所以...

f = Replace (f, " ", "")
Run Code Online (Sandbox Code Playgroud)