gpt4 book ai didi

vba - Excel VBA 使用不同工作表中的查找/替换更新单元格

转载 作者:行者123 更新时间:2023-12-04 20:47:16 30 4
gpt4 key购买 nike

嘿,我有一张 sheet1,其中包含 A 列中的搜索模式列表,以及 B 列中相应的类别名称列表。我有一张 sheet2,其中包含我的银行交易的各种描述列表。

例如,在表 1 中,我有杂货、燃料、娱乐、储蓄,在表 2 中,我有“壳牌服务站、abc 路”、“Coles 超市”等。

I want to find words in the transactions columns, and then replace the found line with a category..



例如。如果我在 Sheet2 中找到“Shell”这个词,我想用“Fuel”这个词替换该行

到目前为止,我已经完成了这项工作,但我不认为这是最有效或最有效的方法。下面是我的代码。
Sub UpdateCats()
Dim x As Integer
Dim FindString As String
Dim ReplaceString As String
Dim NumRows As Integer
'Replace and update Categories
With Sheets("Categories")
.Activate
' Set numrows = number of rows of data.
NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count
' Select cell a1.
Range("A2").Select
' Establish "For" loop to loop "numrows" number of times.
For x = 1 To NumRows
FindString = ActiveCell.Value
ActiveCell.Offset(0, 1).Select
ReplaceString = ActiveCell.Value
ActiveCell.Offset(1, -1).Select

With Sheets("Data")
.Activate
'With Columns(2)
Cells.Replace What:=FindString, Replacement:=ReplaceString, LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
'End With
End With
Sheets("Categories").Activate
Next
End With
End Sub

到目前为止我不喜欢我的代码的原因是因为它在循环中运行时必须不断地在工作表之间切换(激活)。有没有办法更好地做到这一点?

最佳答案

总的来说,我不认为这是一个很好的方法。
使用“ActiveCell”和“.Activate”是一个相当危险的习惯,因为任何更改都会搞砸你的整个代码。尝试使用命名层次结构(名称应用程序-名称工作簿-名称表-动态范围,例如命名范围)。
我个人也不是很喜欢offset函数,不知道大家为什么这么痴迷,修改这种代码比较不透明,很少真的需要。
您可以将整个内容加载到字符串数组中并循环遍历它。它简短易读。

关于vba - Excel VBA 使用不同工作表中的查找/替换更新单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10490147/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com