Recordset:字符串记录为空?

时间:2017-10-15 03:18:14

标签: excel-vba vba excel

我有2个excel工作簿,我使用下面的宏将数据(A1:A20)从一个(WB1)拉到另一个。我有问题,只有数字记录被拉,而字符串记录不是。看起来字段类型被认为是一个数字,只有数字被拉。我应该在代码中改变什么才能解决它?

链接下面的

包含源文件: https://drive.google.com/open?id=0B64seB8-qtdLYk80N3hvX2F6VGc

Private Source As Variant

Sub Copy_Paste()
'copy the data from the source
Source = ThisWorkbook.Path & "\WB1.xlsx"
GetData Source, "Sheet1", "A1:A20", Sheets("Database").Range("A1")
End Sub

Public Sub GetData(Source As Variant, SourceSheet As String, SourceRange As String, TargetRange As Range)
Dim rsCon As Object
Dim rsData As Object
Dim szSQL As String
Dim szConnect As String
'Create the connection string based on excel version
    If Val(Application.Version) < 12 Then
        szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                    "Data Source=" & Source & ";" & _
                    "Extended Properties=""Excel 8.0;HDR=No"";"
    Else
        szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                    "Data Source=" & Source & ";" & _
                    "Extended Properties=""Excel 12.0;HDR=No"";"
    End If
szSQL = "SELECT * FROM [" & SourceSheet$ & "$" & SourceRange$ & "];"

On Error GoTo SomethingWrong
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect
rsData.Open szSQL, rsCon, 0, 1, 1
' Check to make sure we received data and copy the data
If Not rsData.EOF Then
    TargetRange.Cells(1, 1).CopyFromRecordset rsData
Else
    MsgBox "No records returned from : " & Source, vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
rsCon.Close
Set rsCon = Nothing
Exit Sub
SomethingWrong:
    MsgBox "The file name, Sheet name is invalid of : " & Source, vbExclamation, "Error"
On Error GoTo 0
End Sub

1 个答案:

答案 0 :(得分:2)

见这里:https://social.msdn.microsoft.com/Forums/sqlserver/en-US/ce095b10-84a4-4ae3-8944-70a2b53daa44/mixed-data-types-in-excel-column-to-oedb-destination?forum=sqlintegrationservices

您需要在连接字符串中添加IMEX = 1。例如:

szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                "Data Source=" & Source & ";" & _
                "Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

否则,驱动程序猜测您的数据列是数字(基于前几行)并忽略任何非数字值。