2017-10-15 99 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

非常感謝蒂姆! –