gpt4 book ai didi

excel - 查找和替换零星的结果

转载 作者:行者123 更新时间:2023-12-04 20:45:29 28 4
gpt4 key购买 nike

我想创建一个简单的(或者我认为的)宏来重命名工作簿中的单元格。该工作簿包含大约十几张纸。首先,我从 2 个输入框开始,这些输入框要求用户输入旧名称和新名称。然后,我使用宏记录器来确定要在工作簿中替换的正确代码,而不是仅在单个工作表中替换。我操纵代码使用输入框中的字符串来确定“查找内容:”和“替换为:”值。下面是代码。

Option Explicit

'PROCEDURES-----------------------------------------------------------------------------------
Sub Rename_Project()

'---Procedure Description/Notes---------------------------------------------------------------
'Macro Overview:
'Simple macro that will rename all instances of a project in the workbook (all sheets).
'The user will be prompted for the old project name then the new name.

'---Variable Declarations---------------------------------------------------------------------
Dim strPrjNew As String
Dim strPrjOld As String

'---Code--------------------------------------------------------------------------------------
'Launch input box prompting for old PROJECT NAME
strPrjOld = InputBox("Enter existing Project Name:", "Existing Project")
If Len(strPrjOld) = 0 Then Exit Sub 'Pressed cancel

'Launch input box prompting for new PROJECT NAME
strPrjNew = InputBox("Enter NEW Project Name:", "New Project")
If Len(strPrjNew) = 0 Then Exit Sub 'Pressed cancel
'
Selection.Replace What:=strPrjOld, Replacement:= _
strPrjNew, LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False _
, SearchFormat:=False, ReplaceFormat:=False

End Sub

如您所见,这非常简单。我面临的问题是,只有当我手动转到替换命令然后将 'Within:' 选项更改为 Workbook 时,它才会运行。之后我可以整天运行宏而没有问题。有没有办法在宏中将选项设置为 Workbook 而不是 Sheet?我在录制宏时这样做了,但是由于某种原因它似乎没有录制那部分???

如果这在其他地方有所涉及,我提前道歉。我搜索了很多次,但无法找到解决方案……这可能是由于我对要查找的内容缺乏了解。

谢谢!!

最佳答案

而不是使用 Application.Selection将返回与上下文相关的范围的属性(根据您给出的描述,这似乎不是您的目的),我建议使用 Worksheet对象作为替换的引用。

如果要替换工作簿的所有工作表,我建议迭代工作表:

Dim ws As Worksheet
For Each ws In Worksheets
With ws
.Cells.Replace What:=strPrjOld, Replacement:= _
strPrjNew, LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False _
, SearchFormat:=False, ReplaceFormat:=False
End With
Next ws

否则,如果您只想替换一张工作表:
Workseets("sheet1").Cells.Replace What:=strPrjOld, Replacement:= _
strPrjNew, LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False _
, SearchFormat:=False, ReplaceFormat:=False

关于excel - 查找和替换零星的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18500808/

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