1

我有一个格式为“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

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

SJ

附言

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

4

1 回答 1

2

第一个问题是xyzData设置为字符串。当您从 a 填充它时,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 位数字),那么按长度分解字符串可能更简单,但您没有指定这是的情况,所以我没有假设它。

于 2013-04-04T22:48:26.380 回答