使用Excel VBA检索数据并粘贴

时间:2015-06-04 12:01:15

标签: vba

VBA代码

'This function is ur comnad button 
private sub cmdgetData()
call GetData
end sub

这是模块1,用于从配置文件中获取数据。

'Module 1
Public sub GetData()
Dim oExcelConn As ADODB.Connection
'=====
Dim oConn As ADODB.Connection '* Connection String
Dim oRst As ADODB.Recordset '* Record Set
Dim sQuery As String '* Query String
dim sConnStr as string
Dim wb As Workbook, wbCurr as workbook

sConnStr = GetExcelConnStr(thisworkbook.path & "\data\ExcelData.xlsx")

set oConn = new ADODB.Connection


oConn.open sConnStr
set wb = Workbooks.Open ThisWorkbook.Path & "\Template\MyTemplate.xltx"
For iCtr = 1 To Sheet2.Range("Name_Std").Rows.Count
sQuery = "Select * from [Config$A:R] where column = " &                           Sheet2.Range("Name_Std").cells(iCtr,1)
set oRst = new adodb.recordset
oRst.open sQuery, oConn
set wbCurr =  wb.worksheets("Sheet1").Copy After:=Worksheets("Sheet1")
wbCurr.range("A2").cpoyfromRecordset oRst
Next
End Sub

这是模块1,用于从配置文件中获取数据。 这是模块1,用于从配置文件中获取数据。 这是模块1,用于从配置文件中获取数据。 这是模块1,用于从配置文件中获取数据。 这是模块1,用于从配置文件中获取数据。 这是模块1,用于从配置文件中获取数据。

Public Function GetExcelConnStr(sPath As String) As String

Dim sConnStr As String

sConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"

GetExcelConnStr = sConnStr

End Function

1 个答案:

答案 0 :(得分:0)

Set wks = ActiveWorkbook.Worksheets("Template")

' wks.Range("B2").Cells(1, 17).Value


Dim i As Integer
Dim startIndex As String
Dim EndIndex As String
Dim wsName As String
wsName = "temp"

Dim str As String
For i = 1 To 17
   str = wks.Range("B2").Cells(i, 1).Value
   If str = "Grand Total" Then
      EndIndex = wks.Range("B2").Cells(i, 1).Address
      Exit For
   End If
Next i

 startIndex = wks.Range("B2").Cells(1, 1).Address
 EndIndex = wks.Range("B2").Cells(i - 1, 17).Address
 wks.Range(startIndex & ":" & EndIndex).Copy
 ThisWorkbook.Worksheets(wsName).Select
 ActiveSheet.Range("B2").Select
ActiveSheet.Paste