vba 用于读取 Excel 中单元格值并在相应行的第二个工作表中输入给定值的宏代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25813110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Macro code to read value of a cell in Excel & enter a given value in a second sheet on corresponding row
提问by In_Need_Of_Macro_Assistance
Looking for some help with a fairly basic excel macro to read a value in a cell on one Excel sheet and then find that value in a second sheet and enter a pre-defined value into a specified cell in that row.
寻找一些关于相当基本的 excel 宏的帮助,以读取一个 Excel 工作表上单元格中的值,然后在第二个工作表中找到该值,然后在该行的指定单元格中输入一个预定义的值。
To break it down...
为了打破它...
- Read the value of a given cell in sheet_1 (this will be an ID number)
- Go to sheet_2, find the ID number in column_a
- Go to a given column in that row
- Write a pre-defined value into the cell
- 读取 sheet_1 中给定单元格的值(这将是一个 ID 号)
- 转到sheet_2,找到column_a中的ID号
- 转到该行中的给定列
- 将预定义值写入单元格
Thanks!
谢谢!
采纳答案by Daniel
This may point you in the right direction:
这可能会为您指明正确的方向:
Sub FindID()
Dim ID_Number As String
Dim col As Integer
Dim rw As Integer
Dim WS As Worksheet
Set WS = Activeworkbook.Sheets("sheet_2")
ID_Number = Activecell.Value 'reads value of ID_Number in WS 1; assumes you have selected the ID_Number you want to work with
With WS
.Activate
.Range("A1").Activate
End With
WS.Range("A:A").Cells.Find(What:=ID_Number, After:=ActiveCell, LookIn:=xlFormulas, _ 'finds ID_Number in WS 2
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False).Activate
rw = Activecell.Row
col = 'whatever column you want to look at, expressed as an integer; A=1, B=2,...
WS.Cells(rw, col).Value = ID_Number 'write ID_Number to cell
End Sub
You can use the "Find" method of the "Cells" object to search for the column you want to look at, as well, if you want to make your code more dynamic.
如果您想让您的代码更加动态,您也可以使用“Cells”对象的“Find”方法来搜索您想要查看的列。