VBA通过循环读取Excel内的两列

时间:2016-05-16 13:38:20

标签: excel vba excel-vba vbscript

我有这段代码:

Dim cityList() 

Set objExcel = CreateObject("Excel.Application") 

Set objWorkbook = objExcel.Workbooks.Open("C:\Users\xyz\Desktop\Test\Cities.xlsx") 
objExcel.Visible = True 

i = 1 
x = 0 

Do Until objExcel.Cells(i, 1).Value = "" 
ReDim Preserve cityList(x) 
cityList(x) = objExcel.Cells(i, 1).Value 
i = i + 1 
x = x + 1 

Loop 

objExcel.Quit

我有问题使这个像数组有两个条件。我的excel包含两列: 城市日期

Mumbai  22.04.2016
Delhi   23.05.2016
Goa     24.06.2016

我已经设法阅读专栏列并逐一阅读,但我还需要阅读日期和条件如下:

对于City ="孟买"和日期=" 22.04.2016"做点什么....

我对VBA不太熟悉,但必须编写脚本。

是否有人可以帮助我如何在内部添加Date以便他可以读取这两列?

先谢谢

4 个答案:

答案 0 :(得分:2)

这里是对现有代码的快速重写,实现了我认为您所追求的目标:

Dim cityList(1,0)
Set objExcel = CreateObject("Excel.Application") 
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\xyz\Desktop\Test\Cities.xlsx") 
objExcel.Visible = True 
Set oSheet = objWorkbook.Worksheets("Sheet1")   ' set the correct sheet name here
iLastRow = oSheet.Cells(oSheet.Rows.Count, 1).End(xlUp).Row ' determine the last row to look at

For iRow = 1 To iLastRow
    ReDim Preserve cityList(1,iRow-1)                       ' within the loop, extend the array by 1
    cityList(0,UBound(cityList)) = oSheet.Cells(iRow,1)     ' Set the city value
    cityList(1,UBound(cityList)) = oSheet.Cells(iRow,2)     ' Set the date value
Next

' Now you have all the data you can iterate over it like so:
For iLoop = 0 To UBound(cityList,2)
    If cityList(0, iLoop) = "Mumbai" And cityList(1, iLoop) = "22.04.2016" Then
        ' Do whatever you needed to do
    End If
Next

objExcel.Quit

答案 1 :(得分:1)

为什么所有这些循环和redim

Dim cityList as variant, lastRow as Long
lastRow = range("A" & rows.count).End(xlUp).Row
cityList = range("A1:B" & lastrow)

编写和执行的速度要快得多

答案 2 :(得分:0)

' in your code you can capture date values using offset property

ReDim Preserve cityList(x) 
cityList(x) = objExcel.Cells(i, 1).Value 
' = objExcel.Cells(i, 1).Offset(0, 1).Value  ' offset property to capture date 
' As Dave said either you can use Dictionary or 2D arrays to store date. . .
i = i + 1

答案 3 :(得分:0)

我找到了解决方案:

Dim cityList() 

Set objExcel = CreateObject("Excel.Application") 
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\xyz\Desktop\Test\Cities.xlsx") 
objExcel.Visible = True 
i = 1
x = 0 
y = 0

Do Until objExcel.Cells(i, 1).Value = "" 
ReDim Preserve cityList(x)
ReDim Preserve cityDate(y)
cityList(x) = objExcel.Cells(i, 1).Value
cityDate(y) = objExcel.Cells(i, 2).Value

i = i + 1 

x = x + 1 
y = y + 1

Loop 

objExcel.Quit

j = 0

For Each city in cityList

tab = "City"
        datetime = cityDate(j)
        j = j + 1
        count = count + 1
        .....
Next

也许不是最好的解决方案,但是有效!谢谢大家的建议和帮助!