在VBA函数中返回带有上标字符的string

我有一个Excel中的macros,它将十进制度值(赤经)转换成天文小时的angular度与小时(h),分钟(米)和秒(s)。 有什么办法,返回带有上标缩写h,m,s的string?

这是我的Excelmacros:

Function Convert_Hours(Decimal_Deg) As Variant With Application hours_dec = Decimal_Deg / 360 * 24 hours = Int(hours_dec) minutes_dec = hours_dec - hours minutes = Int(minutes_dec) seconds = minutes_dec - minutes Convert_Hours = " " & hours & "h " & minutes & "m " & Round(seconds, 2) & "s " End With End Function 

所以例如在单元格A1我写176.7854和单元格B1 =Convert_Hours(A1) 。 这写11h 0m 0.79s到单元格B1。 但是我想要的是:11 h 0 m 0.79 s

我不想(!)想用VBA引用一些选中的单元格,然后应用类似c.Font.Superscript = True东西,这是在VBA中search上标string时的标准答案。 我的函数Convert_Hours()应该自己返回一个格式化的string。

先谢谢你!

由于一个string只能包含单个字符,而没有格式化,所以没有格式化的唯一方法就是查找代表上标小写字母的Unicode字符。

上标拉丁字母没有完整的Unicode块。 所以我们需要从不同的方块中挑选。 我们可以在Latin_script_in_Unicode中find一个概述。

ʰ和ˢ我们可以在间距修饰符中find。 ᵐ我们可以在语音扩展中find。

如果我们find了字符,我们必须知道如何将它们连接成VBA的string。 为此,可以使用ChrWfunction。 它需要字符的十进制码。

所以

 ... Convert_Hours = " " & hours & ChrW(688) & " " & minutes & ChrW(7504) & " " & Round(seconds, 2) & ChrW(738) ... 

几乎会得到你想要的。 但是上标字母的大小会因为来自Unicode的不同块而有所不同。 所以我宁愿在string中使用默认的字母,然后在格式化上标。 当然这不能在用户定义函数(UDF)中完成。


根据@arcadeprecinct的评论

 ... Convert_Hours = " " & hours & ChrW(&H2B0) & " " & minutes & ChrW(&H1D50) & " " & Round(seconds, 2) & ChrW(&H2E2) ... 

也将使用hex。

简单的build议,总是为我工作:(1)进入编程选项卡,开始录制MACRO; (2)select一个预先添加string的单元格; (3)点击公式字段(屏幕上半部分),selectstring的一部分并标记为上标; (4)停止录制并查看生成的代码。 这将告诉你如何做到这一点。

这里是我刚刚生成的一个例子:

  Sub Macro1() ' ' Macro1 Macro ' ' ActiveCell.FormulaR1C1 = "asd sad ads asd asd asd " With ActiveCell.Characters(Start:=1, Length:=12).Font .Name = "Arial" .FontStyle = "Regular" .Size = 11 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ThemeColor = xlThemeColorLight1 .TintAndShade = 0 .ThemeFont = xlThemeFontMinor End With With ActiveCell.Characters(Start:=13, Length:=7).Font .Name = "Arial" .FontStyle = "Bold" .Size = 11 .Strikethrough = False .Superscript = True .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ThemeColor = xlThemeColorLight1 .TintAndShade = 0 .ThemeFont = xlThemeFontMinor End With With ActiveCell.Characters(Start:=20, Length:=5).Font .Name = "Arial" .FontStyle = "Regular" .Size = 11 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .ThemeColor = xlThemeColorLight1 .TintAndShade = 0 .ThemeFont = xlThemeFontMinor End With Range("D4").Select End Sub 

希望这可以帮助你。