VBA宏代码修改咨询:将固定值替换为TextBox控件值
VBA代码修改方案
直接将代码中的固定值替换为文本框控件的值即可,同时为避免查找不到内容时触发错误,建议增加判断逻辑,以下是修改后的完整代码:
Private Sub CommandButton1_Click() Dim foundCell As Range ' 查找TextBox1.Value对应的内容,替换原固定值"28513" Set foundCell = Cells.Find(What:=TextBox1.Value, After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not foundCell Is Nothing Then foundCell.Activate ' 查找"28537"(用户未要求替换此值,保留原逻辑) Set foundCell = Cells.Find(What:="28537", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not foundCell Is Nothing Then foundCell.Activate ' 将替换值"1509"替换为TextBox2.Value ActiveCell.Replace What:="28537", Replacement:=TextBox2.Value, LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False ' 再次查找"28537" Set foundCell = Cells.Find(What:="28537", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not foundCell Is Nothing Then foundCell.Activate End If End If End If End Sub
关键修改说明
- 将
What:="28513"替换为What:=TextBox1.Value,实现用文本框1的内容作为查找关键词 - 将
Replacement:="1509"替换为Replacement:=TextBox2.Value,实现用文本框2的内容作为替换值 - 增加了
If Not foundCell Is Nothing Then判断,防止当查找不到目标内容时代码报错
内容的提问来源于stack exchange,提问作者Mohamed Shoman
相关产品推荐
相关产品推荐

