【问题标题】:Excel VBA Using .find to find row and column to paste dataExcel VBA 使用 .find 查找行和列以粘贴数据
【发布时间】:2017-04-09 14:29:59
【问题描述】:

我正在尝试查找行号和列号以将数据粘贴到该单元格中。行是要查找的各种指标,列是日期。我更喜欢使用函数,所以我可以简单地调用函数并传递不同的参数。

与此线程相反:How to find cell value based on row and Column ID in excel VBA。我想找到一个单元格的地址。

我目前的代码:

Sub FindMyCell()
    Dim myDate As String
    Dim myMetric As String
    Dim foundRange As Range
    Dim pasteRange As Range
    Dim r As Range, c As Range

    Worksheets("Sheet1").Range("B20").Select

    myDate = Worksheets("Sheet1").Range("B20").Value
    myMetric = Worksheets("Sheet1").Range("B21").Value
    FindCell(myMetric,myDate)
    Inputcell = foundRange.Address


End Sub

Function FindCell(myMetric As String, myDate As String) As String

    With ActiveCell
        r = .Columns("B").Find(myMetric).row
        c = .Rows("3").Find(myDate).Column

        If r = Nothing Or c = Nothing Then
            'errorcount = errorcount + 1
            'Exit Function
        End If

        Set pasteRange = .Cells(r, c).Address
    End With

End Function

我不断收到:编译错误:该行中的参数不是可选的:

Set foundRange = FindCell(myDate & myMetric)

【问题讨论】:

  • 您知道选择 B20 后,ActiverCell.Columns("B") 实际上是工作表上的 C 列,而 ActiverCell.Rows(3) 实际上是工作表上的第 22 行...?您到底在哪里寻找字符串和日期?
  • 'myMetric' 在 B 列,'myDate' 在第 3 行。值在单元格 B20 和 B21 上声明
  • 不,我不是这个意思。您希望 find 从哪里返回值?
  • 好的。我想到的是:搜索 B 列以查找指标。获取行号。然后在第 3 行搜索正确的日期,获取列号。然后我将这些值创建一个 .address,我可以在其中发布一个值。

标签: vba excel function find


【解决方案1】:

您正在连接两个参数。使用逗号分隔它们。

Set foundRange = FindCell(myDate, myMetric)
'the line also has a typo
Inputcell = foundRange .Address

您知道选择 B20 后,ActiverCell.Columns("B") 实际上是工作表上的 C 列,而 ActiverCell.Rows(3) 实际上是工作表上的第 22 行...?

函数不应该使用 ActiveCell 并且您正在偏移搜索范围。 .Find 中的日期可能很棘手。试试这个替代方案。

Option Explicit

Sub FindMyCell()
    Dim myDate As Long
    Dim myMetric As String, inputCell As String

    With Worksheets("Sheet1")
        myDate = .Range("B20").Value2
        myMetric = .Range("B21").Value2

        inputCell = FindCell(.Name, myMetric, myDate)
        Debug.Print inputCell
    End With

End Sub

Function FindCell(wsn As String, myMetric As String, myDate As Long) As String
    Dim r As Variant, c As Variant

    With Worksheets(wsn)
        r = Application.Match(myMetric, .Columns("B"), 0)
        c = Application.Match(myDate, .Rows(3), 0)

        If IsError(r) Or IsError(c) Then
            'errorcount = errorcount + 1
            'Exit Function
        End If

        FindCell = .Cells(r, c).Address
    End With

End Function

【讨论】:

  • 吉普车,这行得通。我尝试了几种不同的 myMetrics 和 myDates,它完美地找到了相交的单元格地址!
  • 你能解释一下wsn和value2吗?所以我可以学习以备将来参考?
  • wsn 是工作表的名称。 Value2 是原始基础数字,不包含日期的区域信息。今天的 .Value242,834,这是自 1899 年 12 月 31 日以来的天数。
猜你喜欢
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多