简体   繁体   English

查找单元格并替换为其他值

[英]Finding cell and replacing with different value

I am writing a spreadsheet to record queries, once the query has been dealt with want to change the status of the entry to closed. 一旦处理完查询后,我想编写一个电子表格来记录查询,希望将条目的状态更改为已关闭。

Currently, on Sheet 1 the user can type the code of the query in and select to close it. 当前,用户可以在工作表1上键入查询的代码,然后选择关闭查询。 I then want to search through Sheet 2 which stores all the records and change the query code to closed by adding a C at the end. 然后,我想搜索存储所有记录的工作表2,并通过在末尾添加C将查询代码更改为关闭。

 Private Sub CommandButton8_Click()
 Dim Findtext As String
 Dim Replacetext As String

 ThisWorkbook.Sheets("Sheet 1").Activate

 Findtext = Sheets("Sheet 1").Range("C25").Value
 Replacetext = Sheets("Sheet 1").Range("E25").Value


 ThisWorkbook.Sheets("Sheet 2").Activate

 Cells.Replace What:=Findtext, Replacement:=Replacetext, LookAt:=xlPart, _
 SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
 ReplaceFormat:=False     
 End Sub

C25 is the code typed by the user and E2 is currently CONCATENATE(C25,"C") At the moment, the changes are being made on sheet 1 and not sheet 2, I have limit experience with VBA so assume I must be missing something out but not sure what it is. C25是用户键入的代码,E2当前为CONCATENATE(C25,“ C”)目前,更改是在工作表1而不是工作表2上进行的,我对VBA的经验有限,因此假设我必须缺少某些内容出来,但不确定是什么。

Try this. 尝试这个。 You don't need to activate the sheets, just add sheet references as below. 您无需激活工作表,只需添加如下工作表引用即可。

Private Sub CommandButton8_Click()

Dim Findtext As String
Dim Replacetext As String

With Sheets("Sheet 1")
    Findtext = .Range("C25").Value
    Replacetext = .Range("E25").Value
End With

Sheets("Sheet 2").Cells.Replace What:=Findtext, Replacement:=Replacetext, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

End Sub

You can simply use the Find method. 您可以简单地使用Find方法。

Also, no need to use .Activate 另外,无需使用.Activate

 Private Sub CommandButton8_Click()

 Dim Findtext As String
 Dim Replacetext As String

 Findtext = Sheets("Sheet 1").Range("C25").Value
 Replacetext = Sheets("Sheet 1").Range("E25").Value

    Dim myCel As Range

    With ThisWorkbook.Sheets("Sheet 2").Cells
        Set myCel = .Find(What:=Findtext, LookAt:=xlWhole)
        myCel.Value = Replacetext
    End With

 End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM