查找当前单元格值并将其替换为单元格编号

时间:2017-06-07 01:17:54

标签: excel-vba excel-2013 vba excel

我对VBA很新。我已经尝试录制我的宏,但似乎无法弄明白。

我希望宏能如下:

在选定的单元格上,我想搜索该值并替换所选单元格“number”的内容。

示例:假设我选择了单元格A1,其值为666我希望它搜索并替换包含666的工作表上的所有单元格为“= A1”。

本质上我希望他们都指向初始细胞。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

基本上,您遍历当前工作表上已使用范围内的单元格并替换单元格值。下面是代码,它将完成你所追求的目标。我评论了每一行,以明确究竟发生了什么。

Sub Test()
'Range variable to use for looping
Dim rng As Range 

'String variable for finding the values.
Dim searchvalue As String 

'We'll loop on the current sheet
With ActiveSheet

    'You need to have a single cell selected, if that's not the case we exit the macro.
    If Selection.Count > 1 Then Exit Sub 

    'Get the value to search for
    searchvalue = Selection.value 

    'Loop over all cells in the sheet that have values.
    For Each rng In .UsedRange 

        'We do not want to overwrite the range from where we search (the selection)
        If Intersect(rng, Selection) Is Nothing Then 

             'And if we find the value that was in the selection
            If rng.value = searchvalue Then

                Then create the =cell we selected formula.
                rng.value = "=" & Selection.Address '
            End If
        End If

    'Next cell in the loop
    Next rng

'And we don't need the activesheet anymore.
End With
End Sub

由于这是非常通用的东西,我建议你阅读一般的Excel VBA编程。一些很好的资源是: