如何在 ExcelVBA 中将整数转换为字符串?

如何在 Excel VBA 中将 整数值“45”转换为 绳子值“45”?

1028084 次浏览

尝试使用 CStr ()函数

Dim myVal as String;
Dim myNum as Integer;


myVal = "My number is:"
myVal = myVal & CStr(myNum);

CStr(45)是所有您需要的(转换字符串函数)

大多数时候,您不需要“转换”; VBA 将为您做安全的隐式类型转换,没有使用类似 CStr的转换器。

下面的代码工作起来没有任何问题,因为变量的类型是 String 和 隐式类型转换为您自动完成!

Dim myVal As String
Dim myNum As Integer


myVal = "My number is: "
myVal = myVal & myNum

结果:

“我的号码是: 0”

你甚至不需要那么花哨,这个也可以:

Dim myString as String
myString = 77

“77”

唯一需要转换的时候是变量 Type 不明确 (例如,Type Variant,或 Cell’s Value(其中 Variant))的时候。

即使这样,如果你使用另一个字符串变量或常量,你也不必使用 CStr函数:

Sheet1.Range("A1").Value = "My favorite number is " & 7

“我最喜欢的数字是7”

所以,实际上,唯一的 稀有的情况是当你真正想要存储一个整数值,到一个变量或单元格值,当 没有也与另一个字符串复合(这是一个非常罕见的副情况,我可能会补充) :

Dim i as Integer
i = 7
Sheet1.Range("A1").Value = i

7

Dim i as Integer
i = 7
Sheet1.Range("A1").Value = CStr(i)

“7”

在我的例子中,没有找到函数 CString。 但是向值中添加一个空字符串也是可行的。

Dim Test As Integer, Test2 As Variant
Test = 10
Test2 = Test & ""
//Test2 is now "10" not 10

不声明变量的最短方法是使用 类型提示:

s$ =  123   ' s = "123"
i% = "123"  ' i =  123

这将不与 Option Explicit编译。类型将不是 Variant,而是 StringInteger

如果您正在拉入的字符串恰好是一个十六进制数字,比如 E01,那么即使您使用 CStr 函数,即使您首先将它存储在 String 变量类型中,Excel 也会将其转换为0。解决这个问题的一种方法是在值的开头附加’。

例如,当从 Word 表中提取值并将它们带到 Excel 中时:

strWr = "'" & WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)

另一种方法是将数值的两个已解析部分拼接在一起:

Cells(RowNum, ColumnNum).Value = Mid(varNumber,1,1) & Mid(varNumber,2,Len(varNumber))

我已经发现这比 CStr()更好的成功,因为在我的经验中,CStr()似乎不能转换来自变量的十进制数。

如果您有一个有效的整数值,并且您的要求是比较值,那么您可以简单地进行如下所示的比较。

Sub t()


Dim i As Integer
Dim s  As String


' pass
i = 65
s = "65"
If i = s Then
MsgBox i
End If


' fail - Type Mismatch
i = 65
s = "A"
If i = s Then
MsgBox i
End If
End Sub

接受的答案适用于较小的数字,最重要的是当您从 Excel 表中获取数据时。因为较大的数字会自动转换为科学数字,即 e + 10。
所以我认为这会给你一个更普遍的答案,我没有检查它是否有任何缺陷。

CStr(CDbl(#yourNumber#))

这将工作的 e + 转换的数字!因为刚才的 CStr(7.7685099559e+11)将显示为“7.7685099559 e + 11”,而不是预期的“776850995590”,所以我宁愿说我的答案将是更一般的结果。

问候, M

enter image description here

    Sub NumToText(ByRef sRng As String, Optional ByVal WS As Worksheet)
'---Converting visible range form Numbers to Text
Dim Temp As Double
Dim vRng As Range
Dim Cel As Object


If WS Is Nothing Then Set WS = ActiveSheet
Set vRng = WS.Range(sRng).SpecialCells(xlCellTypeVisible)
For Each Cel In vRng
If Not IsEmpty(Cel.Value) And IsNumeric(Cel.Value) Then
Temp = Cel.Value
Cel.ClearContents
Cel.NumberFormat = "@"
Cel.Value = CStr(Temp)
End If
Next Cel
End Sub




Sub Macro1()
Call NumToText("A2:A100", ActiveSheet)
End Sub

Refer: MrExcel.com-使用 VBA 将数字转换为文本

也许值得在转换中添加一个修剪,因为整数转换的前导空格用于推断(正符号)和应用(负符号)值。

作为比较:

1/

lsDogsAge = "Barker is " & Cstr(liAgeInteger) & "years old"

2/

lsDogsAge = "Barker is " & Trim(Cstr(liAgeInteger)) & "years old"

1/Barker 是 _ _ 7

2/Barker 是 _ 7

具有讽刺意味的是,这个论坛的软件会自动截断双倍空格,所以我使用了下划线