如何通过VBA代码在工作表上进行search?
我有一个工作表,有2列“关键”和“价值”。 通过VBA代码,我想在Key列上searchInput_key,如果不存在,我将添加新行[input-key] – [input-value]。 我如何编码?
你会从评论中认识到“请为我解决我的问题”的问题不受欢迎。
我会猜测你不知道从哪里开始,会给你一些初步的指导。
转到Google,input“excel vba tutorial”。 你会被提供很多网站。 他们都是不同的,所以尝试几个,find一个适合你的。
试试macroslogging器。 我build立了一个与您的描述相匹配的工作表,打开macroslogging器,select列A,单击Ctrl+F
以获得查找屏幕,并单击选项button向我显示所有选项。 结果是:
看看选项。 例如,案件重要吗? 根据需要select。 我勾选“匹配全部单元格内容”,input“k”并单击“ Find Next
。 光标跳转到包含“k”的单元格。 然后,我closures了macroslogging器。
为我保存的代码是:
Sub Macro1() ' ' Macro1 Macro ' Macro recorded 27/02/2012 by Tony Dallimore ' Columns("A:A").Select Selection.Find(What:="k", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Activate End Sub
这是有效的VBA,但不是很好的VBA。 macroslogging器logging了您执行的每个动作。 它不知道你的意图。 所以我们需要整理这个代码。
关键的变化是:
- 我们不想select列A或激活包含find的值的单元格。
- 我们需要考虑到价值不被发现。
将下面的macros复制到macroslogging器保存其代码的模块中。 我通过修改保存的代码来创build这个macros来创build一个testing工具供您使用。 它要求一个值,在列A中search,并说明是否find该值。 这是你需要的代码的基础。
Sub PlayMacro() Dim Prompt As String Dim RetValue As String Dim Rng As Range Dim RowCrnt As Long Prompt = "" ' The macro recorder has used the active worksheet. This says which ' worksheet is to be used whether it is active or not. Change "Sheet4" ' to the name of your worksheet. With Sheets("Sheet4") ' This will loop forever unless a statement within ' the loop exits the Do. Do While True RetValue = InputBox(Prompt & "Give me a value to look for") 'RetValue will be empty if you click cancel If RetValue = "" Then Exit Do End If ' I do not wish to active the cell containing the required value. ' I want to know where it is. Set Rng = .Columns("A:A").Find(What:=RetValue, After:=.Range("A1"), _ LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) If Rng Is Nothing Then ' The entered value could not be found Prompt = "I could not find """ & RetValue & """" Else ' The entered value was found RowCrnt = Rng.Row Prompt = "I found """ & RetValue & """ on row " & RowCrnt End If Prompt = Prompt & vbLf Loop End With End Sub
现在再次打开macros录音机。 将光标置于列A下任何具有值的行之下。 点击Ctrl+UpArrow
。 光标将跳到列A中的最后一个值。closuresmacros录制器。
保存的代码将如下所示:
Sub Macro2() ' ' Macro2 Macro ' Macro recorded 27/02/2012 by Tony Dallimore ' ' Range("A64").Select Selection.End(xlUp).Select Range("A28").Select End Sub
End(xlUp)
是Ctrl+UpArrow
End(xlUp)
的VBA。 这是find最后使用的行的最简单的方法。
要添加一个新行,如果找不到该值,则要执行此操作:
RowCrnt = .Cells(Rows.Count, "A").End(xlUp).Row + 1 .Cells(RowCrnt,1),Value = "Key" .Cells(RowCrnt,2),Value = "Value"
如果你看其他的问题,你会发现End
有时不会给你你期望的结果。 在一个空列上试一下Ctrl+DownArrow
和Ctrl+UpArrow
,顶部有一个然后两个值的列,底部有一个然后两个值的列和有几个值由空白行分隔的列。
这应该让你开始。 欢迎来到Excel编程。 祝你好运。