2017-10-15 66 views
1

我有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 

回答

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"";" 

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

+0

非常感谢蒂姆! –