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

我有这个代码:

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包含两列:城市date

 Mumbai 22.04.2016 Delhi 23.05.2016 Goa 24.06.2016 

我已经设法阅读列城市,并一一阅读,但我也需要阅读date和条件是这样的:

对于城市=“孟买”和date=“22.04.2016”做些事情….

我不是很熟悉VBA,但脚本必须写。

任何人都可以帮助我如何添加date里面,所以他可以读两列?

非常感谢

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

 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 

为什么所有这些循环和redim

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

编写和执行速度要快得多

 ' 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 

我find了解决办法:

 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 

也许不是最好的解决scheme,但工作! 谢谢大家的build议和帮助!