简体   繁体   中英

How to reference cell from another sheet in Module - Excel VBA?

I have a macro in an Excel workbook that updates date from Sheet1 into SQL by clicking a button in Sheet3. Sheet3 also have cells used as parameters during the update process.

Currently, the macro is placed in a module and my SQL statement is as follows:

sSQLUpd = "update [table1].[dbo].[Plan] set [Plan_QTY] = " & Plan & "_
           where [MacID] = " & Mac & " and [ModelID] = " & Mdl & " and [Date] = " & dt & "_
           and DATEPART(year,[Date])= " & Sheets("Sheet3").Cells(3, 3).Value & "_
           and DATEPART(month,[Date])= " & Sheets("Sheet3").Cells(3, 6).Value & ""
conn.Execute sSQLUpd

But when I test the code I keep getting "Subscript out of range" in my error handler.

The SQL structure is fine, since I tested it by replacing the parts:

DATEPART(year,[Date])= " & Sheets("Sheet3").Cells(3, 3).Value & "

and

DATEPART(month,[Date])= " & Sheets("Sheet3").Cells(3, 6).Value & "

with actual numbers and the data can pass.

So it's safe to assume that the codes referencing the cells in Sheet3 have issue. Perhaps it doesn't want to play nice when placed in a module?

I even tried different variations as well:

DATEPART(year,[Date])= " & Sheets("Sheet3").range("C3").Value & "

No dice....

Anything I can do to modify it?

Wait... Never mind. I figured out what went wrong. All I needed to do was change Sheets("Sheet3") into Sheet3 only:

DATEPART(year,[Date])= " & Sheet3.Cells(3, 3).Value & "

Its always the simple stuff that screws with me. :p

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