简体   繁体   中英

Finding a cell in an Excel file with VBA

I never asked a question here but I'm desperate and I can't find the solution to my problem.

I am programming with VBA for Access. I must get the value of a specific cell in a specific Excel file. To get this value I must Find the cell first, and thus comes my problem.

When I try to use the .Find method to get the column of the cell I need, it gives me error "13", type incompatibility.

This is what I'm doing:

Dim col As Integer
Dim appExcel As Excel.Application
Dim wbExcel As Excel.Workbook
Set appExcel = CreateObject("Excel.Application")
appExcel.Visible = True
Set wbExcel = Workbooks.Open("J:\EXPLOITATION\INDEXATION des tarifs\2017\Indexation GO client 2017.xls")
appExcel.Sheets("Indices GO 2017").Select
col = appExcel.Range("A22:Z22").Find("mai-2017", xlWhole, False, False).Column

Basically like this I get the column of the cell (because the cell I want is in the same column as the cell I found), then I will do the same to find the row, then I can get the value of the cell with the row and column.

On a side note, how can I open an excel file that starts with the name "Indexation" followed by anything else? (what in sql would be *)

Thank you so much, I need this to finish my thesis. Cordially, Voodoo.

 .Find("mai-2017", xlWhole, False, False) 

Remove the useless parameters, first off they are misplaced. for example the second parameter should be a Range (cell) where to start the search. xlWhole is a number, not a range. Its position is the 4th in the parameter list, not the second.

The parameters are also of the wrong type. False for what, which parameters. anyway, it doesn't seem that you need anything else, just the first parameter, so let's make life easier:

.Find("mai-2017")

If you really need to match whole cell at most, this:

.Find("mai-2017",, xlWhole)

Finally, as per @ErikvonAsmuth in the comments section, a match wont be found if the searched cell is formatted as date, because its inner value is actually a number. In that case, try to match the date type, like this:

.Find(DateValue("May-2017"))

Since your row has dates, try this to match the first occurrence of a date within may 2017 in the row:

col = appExcel.Evaluate("AGGREGATE(15, 6, COLUMN('Indices GO 2017'!22:22)" & _
"/ (MONTH('Indices GO 2017'!22:22)=5)/(YEAR('Indices GO 2017'!22:22)=2017), 1)")

You can easily adapt it to return the first date within any given month ( 5 corresponds to May) in row 22.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM