如何将剪贴板放入2D数组(excel vba)

时间:2014-11-28 08:20:56

标签: arrays excel vba excel-vba

我对Excel VBA非常陌生,我希望从剪贴板中将文本转换为2D数组,并带有第一个分隔符vbNewLine和第二个分隔符空间。如何创建未知大小的2D数组?我可以分割一个数组,比如下面我失败了吗?

Sub CommandButton1_Click()
    Dim DataObj As MsForms.DataObject
    Set DataObj = New MsForms.DataObject
    Dim strArray() As String

    On Error GoTo ERRROR

    '~~> Get data from the clipboard.
    DataObj.GetFromClipboard

    '~~> Get clipboard contents
    myString = DataObj.GetText(1)

    '~~> Split into string, delimiter vbNewLine
    strArray = Split(myString, vbNewLine)

这里我失败了

    '~~> Split each strArray and store in strArray2, delimiter " ".
    Dim strArray2() As String
    For ii = LBound(strArray2) To UBound(strArray2)
        strArray2(ii) = Split(strArray(ii))
    Next ii

Exit Sub
ERRROR:
    If Err <> 0 Then    
    'Handel error
End If
End Sub

1 个答案:

答案 0 :(得分:2)

你这样做是错误的。

这是你在尝试什么? (的 UNTESTED

Sub CommandButton1_Click()
    Dim DataObj As MsForms.DataObject
    Dim strArray, strArray2
    Dim i As Long, j As Long
    Dim myString As String

    On Error GoTo ERRROR

    Set DataObj = New MsForms.DataObject

    '~~> Get data from the clipboard.
    DataObj.GetFromClipboard

    '~~> Get clipboard contents
    myString = DataObj.GetText(1)

    '~~> Split myString, delimiter vbNewLine
    strArray = Split(myString, vbNewLine)

    '~~> Split each strArray and store in strArray2, delimiter " ".
    For i = LBound(strArray) To UBound(strArray)
        strArray2 = Split(strArray(i))

        For j = LBound(strArray2) To UBound(strArray2)
            Debug.Print strArray2(j)
        Next j
    Next i

    Exit Sub
ERRROR:
    If Err <> 0 Then Debug.Print Err.Description
End Sub