vba 删除VBA excel中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10574000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:08:18  来源:igfitidea点击:

Remove whitespace in VBA excel

excelvba

提问by BILL

I have some code for move text from cell to cell

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

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

But variable f has "F 51" value instead of "F51".

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

How solve this problem ? p.s. It's my first code on vba.

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

回答by brettdj

You should be using
CStr
not
Str

你应该使用
CStr
not
Str

Then no workaround is needed for removing an unncessary space

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

ie

IE

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

From Excel help for Str

来自 Excel 帮助 Str

When numbers are converted to strings, a leading space is always reserved for the sign of number.

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

回答by Marc

You could TRIM()the toIndexor REPLACEspaces in the end result, i.e.

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

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

example lifted from here: http://www.techonthenet.com/excel/formulas/replace.php

从这里举起的例子:http: //www.techonthenet.com/excel/formulas/replace.php

So...

所以...

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