我正在尝试找到一个行和列号来粘贴该单元格中的数据。行是要查找的各种度量标准,列是日期。我更喜欢使用它的函数,所以我可以简单地调用函数传递不同的参数。
与此主题相反: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)
答案 0 :(得分: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,而是偏移搜索范围。在FIN中,日期可能很棘手。试试这个替代方案。
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