Using Match and Address functions within Macro or VBA

吃可爱长大的小学妹 提交于 2019-12-08 04:11:07

问题


I have two worksheets, I want to use a value in sheet to_approve to lookup against column A in sheet submitted, then identify the cell reference so I can paste a value in the cell adjacent (column B).

I have used the following to identify the cell reference, but I don't know how to use it in VBA code.

=ADDRESS(MATCH(To_Approve!D19,Submitted!A:A,0),1,4,1,"submitted")

回答1:


While many functions can be used in VBA using Application.WorksheetFunction.FunctionName ADDRESS is not one of these (MATCH is)

But even it it was available I would still use a Find method as below as it:

  • gives you the ability to match whole or part strings, case sensitive or not
  • returns a range object to work with if the value is found
  • readily handles a no match
  • you can control the point in the range being search as to where the search starts
  • multiple matches can be returned with FindNext

something like

Sub GetCell()
 Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = Sheets("submitted")
    Set rng1 = ws.Columns("A").Find(Sheets("To_Approve").[d19], , xlValues, xlWhole)
    If Not rng1 Is Nothing Then
        MsgBox rng1.Address & " in sheet " & ws.Name
    Else
        MsgBox "not found", vbCritical
    End If
End Sub



回答2:


This example should give you an idea of how to find a corresponding value on another sheet and place a second value in the the column to the left. When using VBA, it is not necessary to select cells and then paste; you can directly enter a value into a range (cell) object.

Sub TransferValue()
    Dim rngSearch As Range
    Dim rngFind As Range
    Dim dValue As Double
    ' initialization
    Set rngSearch = Worksheets("to_approve").Range("D19")
    dValue = Date
    ' find the match & insert value
    Set rngFind = Worksheets("submitted").Columns(1).Find(What:=rngSearch.Value)
    If Not rngFind Is Nothing Then
        rngFind.Offset(ColumnOffset:=1).Value = dValue
    End If
End Sub

(Note: dValue is a placeholder for whatever value you want to enter.)



来源:https://stackoverflow.com/questions/8398930/using-match-and-address-functions-within-macro-or-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!