【发布时间】:2018-07-24 12:02:19
【问题描述】:
我做了一些研究,没有发现任何类似的问题。
我有一个 VBA 宏,它可以导入一个 .CSV 文件,其中包含设备发送的电报。
在这个宏的末尾,我想创建一个图表,其中 x 轴上已用的时间和对应于电报的值。
问题是这个值可以是不同的类型:十六进制、布尔值、整数......而且它们不遵守标准的 Excel 数字格式,这意味着它们不能用于创建图形。 以下是一些示例(在值周围使用 " 以显示其开始和结束):
- 十六进制:“A7 C8”
- 布尔值:“$00”或“$01”
- 百分比:“30 美元”
And here is an example of data, with custom time format and boolean value
到目前为止,这是我的相关代码,我尝试转换为自定义类型,然后转换回数字以获取通用数字数据类型:
If wsRes.Range("R1").Value Like "$##" Then
wsRes.Range("R1:R" & plotLine).NumberFormat = "$##"
wsRes.Range("R1:R" & plotLine).NumberFormat = General
End If
If wsRes.Range("R1").Value Like "??[ ]??" Then
Dim valArray(1) As String
For i = 1 To plotLine Step 1
valArray = Split(wsRes.Range("R" & i), " ")
wsRes.Range("R" & i).Value = ToInt32(valArray(0) + valArray(1), 16)
wsRes.Range("" & i).NumberFormat = General
Next i
End If
我还不能用 hexa 对其进行测试,但是转换技巧不适用于百分比/布尔值
编辑:
首先,感谢您的回答。
这是我为所有感兴趣的人准备的最终代码,改编自 Vityata 的。
如果需要,此方法将允许轻松添加其他数据类型。
Sub TestMe()
Dim RangeData as String
Set wsRes = ActiveWorkbook.Sheets("Results")
For i = 1 To plotLine Step 1 'plotLine is the last line on which I have data
DetectType wsRes.Range("R" & i).Value, i
Next i
RangeData = "Q1:R" & plotLine
CreateGraph RangeData 'Call My sub creating the graph
End Sub
Public Sub DetectType(str As String, i As Integer)
Select Case True
Case wsRes.Range("R" & i).Value Like "??[ ]??"
wsRes.Range("R" & i).Value = HexValue(str)
Case wsRes.Range("R" & i).Value Like "?##"
wsRes.Range("R" & i).Value = DecValue(str)
Case Else
MsgBox "Unsupported datatype detected : " & str
End
End Select
End Sub
Public Function HexValue(str As String) As Long
Dim valArray(1) As String 'Needed as I have a space in the middle that prevents direct conversion
valArray(0) = Split(str, " ")(0)
valArray(1) = Split(str, " ")(1)
HexValue = CLng("&H" & valArray(0) + valArray(1))
End Function
Public Function DecValue(str As String) As Long
DecValue = Right(str, 2)
End Function
【问题讨论】:
-
欢迎来到 Stack Overflow:请阅读 How to ask a good question,然后编辑您的问题并确保询问 good, clear, concise question,包括代码、预期行为以及问题所在......然后我们可以尝试帮助
-
我认为有可能,如果您编写 3 个布尔函数,取决于变量是否为
IsHex()、IsBoolean()和“IsPercentage()”。 -
更新了我使用的相关代码
标签: vba excel variant custom-data-type