代码示例
Sub getLookup()
GetData "\\myserver\SourceFile.xls", "2015", "A3:AW4", Worksheets("Lookup").Cells(3, 1), True
end Sub
我多次使用getdata将一系列数据从已关闭的工作簿复制到我当前的工作簿中,除了我的源电子表格“2015”上的这个特定范围外,它似乎在Excel 2010中正常工作,getdata返回来自源文件和空单元格(B3,D3,F3)的实际值,它返回F2,F4,F6等值。数字似乎对应于列号。我检查源文件(在表“2015”,第3行)单元格B3,D3,F3看起来是空的。
它甚至在单元格(4,A)上显示F1,其中源文件在该单元格中具有实际值。什么是F1,F2,F4,F6?它们来自哪里?
随机地,它会在目标表单上为一对值附加1,2,3等数字。知道如何解决这个问题吗?
谢谢,
这是子GetData( - 有效,但有一些奇怪的F1,F2,F4值..)
Sub GetData(SrcFile$, SrcSheet$, SrcRange$, rTgt As Range, fHdr As Boolean)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim a&
Dim cnct$
'Initialize a variable for the connection string
cnct$ = "DRIVER={Microsoft Excel Driver (*.xls)}; DBQ=" & SrcFile$
'Initialize connection object
Set cn = New ADODB.Connection
With cn
'Open the database connection
.Open cnct$
'Execute the query
Set rs = .Execute("[" & SrcSheet$ & "$" & SrcRange$ & "]")
End With
'Initialize a variable for the upper left cell of the target range
Set rTgt = rTgt.Cells(1)
With rs
'Determine whether to get the field header
If fHdr Then
'Loop across the fields
For a& = 0 To .Fields.Count - 1
'Get the field names
rTgt.Offset(0, a&).Value = .Fields(a&).name
Next a&
'Advance the target pointer to the next available row in the destination worksheet
Set rTgt = rTgt.Offset(1, 0)
End If
'Apply the CopyFromRecordset method
rTgt.CopyFromRecordset rs
'Close the RecordSet
.Close
End With
'Close the database connection
cn.Close
'Recover memory from object variables
Set cn = Nothing
Set rs = Nothing
End Sub