如何给NumberFormat添加引号
给定一个文本框的输入,你会得到一个字符串值,例如“公斤”。
为了将其用作 NumberFormat 后缀
您需要用引号将单位字符串括起来。
你可以通过分配来做到这一点
Selection.NumberFormat = "0" & """" & Cust_un & """"
或者
Selection.NumberFormat = "0" & Chr(34) & Cust_un & Chr(34)
请注意,VBA 不能将单引号 (") 解释为字符串,
也不是由开始和结束引号括起来的单引号 (""")。
你必须在周围的引号中包含一对引号,即"""" 以使其理解。
替代方案使用 Chr() 函数
返回包含与指定字符代码 34 关联的字符的字符串,即双引号字符。
您可能更喜欢使用帮助函数来返回正确的 NumberFormat,例如
Function getNumberFormat(ByVal unit As String, Optional NumFmt As String = "0 ") As String
unit = Replace(unit, Chr(34), vbNullString) ' remove existing double quotes
getNumberFormat = NumFmt & Chr(34) & unit & Chr(34) ' build NumberFormat including quotes around unit
' or: getNumberFormat = NumFmt & """" & unit & """"
End Function
调用示例
假设您的Custom_unit() 过程驻留在UserForm 代码模块中,使用Me.TextBox1.Text 来引用当前的用户窗体实例而不是引用用户窗体的默认实例。示例调用如下:
Sub Custom_unit()
Selection.NumberFormat = getNumberFormat(Me.TextBox1.Text)
End Sub
顺便说一句:在大多数情况下,最好避免选择引用,c.f. How to avoid using Select in VBA?