如何从Excel工作表中读取数据并将其存储到用户定义的变量中

时间:2016-06-02 18:11:37

标签: excel-vba vbscript vba excel

我创建了一个代码来修改日期,方法是使用变量名称Date添加特定的天数。 现在我有几个文本,包括excel表中的几个不同的日期,我想阅读然后修改并再次重写成相同的excel表。

为此,我创建了一个代码,但是我无法将从Excel工作表中读取的数据加载到变量中。

请建议并提供代码/查询如何从Excel工作表中读取数据并将其存储到用户定义的变量中

2 个答案:

答案 0 :(得分:2)

试试这个例子 值存储在rowData变量

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\VBScriptTrainee\Teams.xlsx")
objExcel.visible=True

rowCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Rows.count
colCount=objExcel.ActiveWorkbook.Sheets(1).UsedRange.Columns.count

Msgbox("Number of Rows are    " & rowCount)
Msgbox("Number of columns are " & colCount)

intRow = 1
intCol = 1
rowData=null


  for intRow=1 to rowCount  step 1


    for intCol=1 to colCount step 1 

       rowData = rowData & " " & objExcel.Cells(intRow, intCol).Value

    next

       rowData = rowData & vbnewline

  next


Msgbox(rowData)

objExcel.Quit
set objExcel=nothing

答案 1 :(得分:1)

如果您在单列中的Excel中有日期,列名为 '重数据&#39 ;.我们可以使用ADO连接字符串取出示例代码。以下是VBS代码示例。

filelocation = "D:\New Microsoft Excel Worksheet.xlsx"
SheetName = "Sheet1"
column_name = "re_data"
row_number = 8

'Create connection
Set conn = CreateObject("ADODB.Connection")
'Create Record Set
Set recordset = CreateObject("ADODB.Recordset")
'Connection String
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filelocation & ";Extended Properties = Excel 12.0 Macro;"
On Error Resume Next
'Connection Open
conn.Open
query   = "SELECT * FROM " & "[" & SheetName & "$] "
recordset.Open query, conn, 3, 3


Count = 1
Do Until recordset.EOF Or Count = row_number
Output_variable =  recordset.Fields.Item(column_name).Value
recordset.MoveNext
Count = Count + 1
Loop

MsgBox Output_variable
recordset.Close
conn.Close