Excel VBA存储SQL选择内容到剪贴板

时间:2018-06-06 15:42:34

标签: excel-vba vba excel

我尝试在Excel中编写VBA代码(在UserForm中单击命令按钮时)以运行SQL查询并将结果存储到Windows剪贴板。数据将是一列,包含多个记录。

这是我尝试过的代码,但是收到错误: 运行时错误' 13': 类型不匹配

Private Sub CommandButton4_Click()

    Dim cn      As Object   'Connection
    Dim rs      As Object   'Recordset
    Dim vAry    As Variant  'Variant Array

    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    cn.Open "Driver={MySQL ODBC 5.3 Unicode Driver};server=10.0.0.2;" & _
            "database=db uid=user; pwd=password;Port=3306"
    rs.Open "Select Device_ID From returns Where Status = 'A';", cn
    vAry = rs.GetRows

    rs.Close
    cn.Close

    Set rs = Nothing
    Set cn = Nothing

    Set myData = New DataObject
    myData.SetText vAry
    myData.PutInClipboard
    MsgBox ("data has been copied to clipboard")

End Sub

1 个答案:

答案 0 :(得分:0)

我通过添加/修改代码来修复错误,以将数组变体转换为字符串:

Dim strData As String
For i = 0 To UBound(vAry, 2) - LBound(vAry, 2)
    strData = strData & vAry(0, i) & vbCrLf
Next

Set myData = New DataObject
myData.SetText strData
myData.PutInClipboard
MsgBox ("data has been copied to clipboard")