我有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
答案 0 :(得分:2)
您需要在连接字符串中添加IMEX = 1。例如:
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Source & ";" & _
"Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"
否则,驱动程序猜测您的数据列是数字(基于前几行)并忽略任何非数字值。