简体   繁体   English

如何从Module-Excel VBA中的另一个工作表引用单元格?

[英]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. 我在Excel工作簿中有一个宏,可通过单击Sheet3中的按钮将日期从Sheet1更新为SQL。 Sheet3 also have cells used as parameters during the update process. Sheet3还具有在更新过程中用作参数的单元格。

Currently, the macro is placed in a module and my SQL statement is as follows: 当前,宏放置在模块中,而我的SQL语句如下:

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: SQL结构很好,因为我通过替换以下部分对其进行了测试:

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. 因此,可以安全地假设引用Sheet3中单元格的代码有问题。 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: 我要做的只是将Sheets(“ Sheet3”)更改为Sheet3:

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

Its always the simple stuff that screws with me. 它总是与我联系的简单东西。 :p :p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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