查找当前单元格值并将其替换为单元格编号
Find and replace current cell value with cell number
我对 VBA 很陌生。我已经尝试录制我的宏,但似乎仍然无法弄明白。
我想要以下宏:
在 selected 单元格上,我想搜索值并替换 selected 单元格 "number".
找到的值
示例:假设我 select 单元格 A1 及其值为 666 我希望它搜索并替换 sheet 上包含 666 的所有单元格为“=A1”。
本质上我希望它们都指向初始单元格。
感谢您的帮助。
基本上,您循环遍历当前 sheet 所用范围内的单元格并替换单元格值。下面是将完成您所追求的代码。我对每一行都进行了评论,以明确到底发生了什么。
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 编程的一般知识。一些很棒的资源是:
- Ozgrid
- Rondebruin他的网站
- Chip Pearson他的网站
我对 VBA 很陌生。我已经尝试录制我的宏,但似乎仍然无法弄明白。
我想要以下宏:
在 selected 单元格上,我想搜索值并替换 selected 单元格 "number".
找到的值示例:假设我 select 单元格 A1 及其值为 666 我希望它搜索并替换 sheet 上包含 666 的所有单元格为“=A1”。
本质上我希望它们都指向初始单元格。
感谢您的帮助。
基本上,您循环遍历当前 sheet 所用范围内的单元格并替换单元格值。下面是将完成您所追求的代码。我对每一行都进行了评论,以明确到底发生了什么。
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 编程的一般知识。一些很棒的资源是:
- Ozgrid
- Rondebruin他的网站
- Chip Pearson他的网站