0

I have the following snipet in Excel 2013/VBA. The code is a very simple random cell/row generator which then displays the output in a text box. In the snippet below Excel/Vba is adding a space between A and the random numebr for example:

"A 14"

where the expected out put was

"A14"

I've gotten around this using the Replace() function, however I'm wondering why this behaviour occurs i the first place. Is it to do with the Str() function?

Private Sub btnRetrieve_Click()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("CenRaw")

Dim k As Long
Dim selectedRow As String

k = sh.Range("A2", sh.Range("A2").End(xlDown)).Rows.Count
aRandNum = Int((k - 2) * Rnd + 2)
selectedRow = Replace("A" & Str(aRandNum), " ", "")
tbOne.Text = selectedRow
selectedRow = vbNullString

End Sub
0

2 Answers 2

3

VBA already has a function for casting to string that doesn't include leading spaces:

tbOne.Text = "A" & CStr(aRandNum)

There are similar functions for casting to other data types too:

  • CBool() -> Boolean
  • CInt() -> Integer
  • CLng() -> Long
  • CDbl() -> Double
  • CDate() -> Date
  • CDec() -> Decimal

to name just a few other examples

Although if you're working with a textbox, the value being assigned is implicitly a string and so the numeric value would show as a string anyway.

Sign up to request clarification or add additional context in comments.

Comments

1

Please see this article on MSDN:

vba str leading spaces

The easier way is to use: LTrim$(aRandNum)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.