VBA Excel:Dec2Hex不止一个地方

时间:2014-08-15 14:45:59

标签: excel vba excel-vba

在宏(如下所示)中,我将一行单元格从十进制转换为十六进制。当我使用正常的Dec2Hex转换(不在VBA中)时,我可以获得两个位置(8 - > 08)。但是,当我使用Dec2Hex转换IN VBA时,我似乎无法获得2个位置,直到我实际需要字符(8 - > 8 BUT 10 - > 0A)。我怎么能强迫最后一个角色而不只是添加0.谢谢!

关注

我注意到的一件有趣的事情是,如果你查看宏,我会在每个十六进制值之后添加一个空格。但是,在查看生成的文件时,仅在存在两个字符时才添加空格。

样本

F3 07 00 31 FA 10 //

F3 07 00 31 FB 20 //

F3 07 00 31 FC 00 //

F3 25 00 31 FF 830B 5114 //< - 注意奇数间距。它应该看起来像...... 08 03 0B ......

F3 07 00 31 FA 11 //

Private Sub CommandButton3_Click()

Dim fso As New FileSystemObject
Dim stream As TextStream
Dim FilePath As String
Dim saveDialog As Variant
Dim hexVal As String
Dim updateRate As String

'"N" is selected elsewhere by the user and simply dictates how far down a row cells are active     


For i = 4 To N + 3
    Cells(3, i) = Application.WorksheetFunction.Dec2Hex(Cells(2, i), 2) & " "
Next i

For i = 4 To N + 3
    hexVal = hexVal & Cells(3, i)
Next i

updateRate = ComboBox1.Value

saveDialog = Application.GetSaveAsFilename(FileFilter:="Script Files(*.us1),*.us1")

    Set stream = fso.OpenTextFile(saveDialog, ForWriting, True)

        stream.WriteLine "F3 07 00 31 FA 10 // "
        stream.WriteLine "F3 07 00 31 FB " + updateRate + " // "
        stream.WriteLine "F3 07 00 31 FC 00 // "
        stream.WriteLine "F3 25 00 31 FF " + hexVal + "// "
        stream.WriteLine "F3 07 00 31 FA 11 // "

    stream.Close

End Sub

2 个答案:

答案 0 :(得分:1)

我认为问题是单元格3,i是数字或一般的。这些中的任何一个都会截断前导零。但是,如果将单元格格式更改为TEXT,则在写出文件之前,前导零不会被截断。

答案 1 :(得分:0)

您做到了:

> For i = 4 To N + 3
>     Cells(3, i) = Application.WorksheetFunction.Dec2Hex(Cells(2, i), 2) & " " 
> Next i
> 
> For i = 4 To N + 3
>     hexVal = hexVal & Cells(3, i) 
> Next i

首先,VBA(Excel)具有“ hex()”功能,为什么要使用worksheetfunction.dec2hex? 其次,为什么要使用单元格来存储十六进制以供以后检索并插入到十六进制中?

您可以将两者替换为:

For i = 4 To N + 3
    hext = hex(cells(2,i)) & " "
    Cells(3, i) = hext
    hexVal = hexVal & hext
Next i

如果希望十六进制值中的偶数个数字,例如“ B”变为“ 0B”,3FC变为03FC,则:

For i = 4 To N + 3
    hext = hex(cells(2,i)) & " "
    if len(hext) Mod 2 = 0 then hext = "0" & hext
    Cells(3, i) = hext  ' if you really need Cells(3,i) to store it
    hexVal = hexVal & hext
Next i