使用变量查找单元格位置(行,列)

时间:2016-08-10 14:08:42

标签: excel-vba macros vba excel

我有一张Excel表格,其中一列的日期如下:

enter image description here

我的工作是找到今天的职位(单元格,专栏)

我正在使用的脚本:

Sub MacroExample()    
 Dim a As Variant   
 Dim column_Position As Variant  
 Dim row_Position As Variant   
 a = Format(Date - 1, "MM\/dd\/yyyy")   
 'MsgBox "The Value of a : " & a    
 Dim oRange          As Range   
 Set oRange = Worksheets(1).Range("A1:Z10000").Find(a, lookat:=xlPart)

 'MsgBox oRange.Address    
 MsgBox column_Position   
 MsgBox row_Position    
End Sub

我的输出应该是:

column_Position = 5 
row_Position = 1

2 个答案:

答案 0 :(得分:1)

如果我理解你的要求,我希望这会有所帮助。此代码应该在指定的搜索范围内找到今天第一次出现的日期。

Sub testDate()

Dim a As Variant
Dim column_Position As Variant
Dim row_Position As Variant

'get today's date, formatted m/d/yyyy
a = Format(Date, "m/d/yyyy")

Dim oRange As range
Dim myCell As range

'set a range to look through
Set oRange = Worksheets(1).range("A1:Z10000")

'check each cell value if it contains today's date. If so, capture the column and row and
'exit the loop.
For Each myCell In oRange

    If InStr(1, myCell.Value, a) Then
        column_Position = myCell.column
        row_Position = myCell.Row
        Exit For
    End If
Next myCell

'display the column and row position, if wanted.
MsgBox "Column Position is " & column_Position & vbNewLine & "Row Position is " & row_Position

End Sub

Code Result

我不能说这是多么有效,但它应该有用。

答案 1 :(得分:0)

如果您在更大的字符串中查找String,这将有效:

Sub MacroExample()
    Dim a As String

    a = Format(Date - 1, "MM/dd/yyyy")
    MsgBox "The Value of a : " & a
    Dim oRange As Range
    Set oRange = Sheets(1).Range("A1:Z10000").Find(what:=a, lookat:=xlPart)
    MsgBox oRange.Column
    MsgBox oRange.Row
End Sub

enter image description here

<强> 注意:

日期包括所需的前导零。