【问题标题】:VB - Split String of Serial Data and Log Separately Into ExcelVB - 拆分串行数据字符串并分别记录到 Excel
【发布时间】:2013-04-04 22:42:12
【问题描述】:

我有一个格式为“X0507Y0512Z0413”的数据字符串。我正在使用 VB 从 pic 微控制器读取数据,并使用网络上的 VB 脚本将数据加载到 excel 中。我可以以上述形式将第一行数据放入电子表格的第一个单元格中。但是我希望将此字符串分成三列 X、Y 和 Z 并从每个变量的开头删除字母。它还必须一次读取最多 20 秒的数据,因此每个值都需要附加到前一个值。到目前为止,这是我的 VB 脚本,我尝试了 Split() 命令并收到错误 13 类型不匹配。

Private Sub CommandButton3_Click()

   Dim intPortID As Integer ' Ex. 1, 2, 3, 4 for COM1 - COM4
   Dim lngStatus As Long
   Dim strData   As String
   Dim xyzData As String

   intPortID = 4
   lngStatus = CommRead(intPortID, strData, 1)
   xyzData = Split(strData, "X""Y""Z")
   Range("A2,B2,C2").Value = xyzData


End Sub

我是一个新手,所以这可能是一个非常简单的修复,如果它看起来微不足道,请道歉。任何建议都会很棒。

S.J

PS

如果每个变量用逗号分隔会更简单吗?

【问题讨论】:

  • 这不是VB.NET,看起来像VB6

标签: excel vb6 split uart


【解决方案1】:

第一个问题是xyzData被设置为字符串。当您从 Split 填充它时,您需要一个数组:

Dim xyzData() as String

我想不出一种简单的方法来在 VBA 中进行拆分,因为您每次都按不同的字符进行拆分 - 它需要一个定制的函数来处理它。以下作品 - 我的 VBA 有点生锈,所以它可能会更整洁,但我认为它有效:

Private Function SplitXYZ(strData As String) As String()

    Dim pos1 As Integer
    Dim pos2 As Integer
    Dim char As String
    Dim i As Integer

    Dim ret() As String
    Dim retCount As Integer
    ReDim ret(0)

    For i = 1 To Len(strData)

        'Get and check the character from the string
        char = Mid(strData, i, 1)
        If char = "X" Or char = "Y" Or char = "Z" Then

            'Set the positions for the new range
            pos1 = pos2
            pos2 = i

            'If the range is valid then add to the results
            If pos1 > 0 Then
                ReDim Preserve ret(retCount)
                ret(retCount) = Mid(strData, pos1 + 1, pos2 - pos1 - 1)
                retCount = retCount + 1
            End If

        End If
    Next i

    'Add any final string
    ReDim Preserve ret(retCount)
    ret(retCount) = Mid(strData, pos2 + 1, Len(strData) - pos2)

    SplitXYZ = ret


End Function

使用起来很简单:

Private Sub Test()

   Dim strData   As String
   Dim xyzData() As String

   strData = "X0507Y0512Z0413"
   xyzData = SplitXYZ(strData)

End Sub

然后如何使用拆分数组取决于您。

另一件事:如果您可以假设字符串中的每条数据长度相同(即前面有字母的 4 位数字),那么按长度分解字符串可能会更简单,但您没有指定确实是这样,所以我没有假设。

【讨论】:

  • 这是一种享受,但是需要找出一种方法将每个拆分字符串放入相应的单元格中,这应该不会太难。有结果时会更新。要感谢 Jon Egerton,您的快速回复和洞察力非常有帮助,我赞扬您,谢谢。
猜你喜欢
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多