Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespace in VBA excel

Tags:

excel

vba

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".

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

like image 473
BILL Avatar asked Nov 29 '22 17:11

BILL


2 Answers

You should be using
CStr
not
Str

Then no workaround is needed for removing an unncessary space

ie

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

From Excel help for Str

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

like image 139
brettdj Avatar answered Dec 05 '22 16:12

brettdj


You could TRIM() the toIndex or REPLACE spaces in the end result, i.e.

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

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

So...

f = Replace (f, " ", "")
like image 40
Marc Avatar answered Dec 05 '22 15:12

Marc