2013-08-29 30 views
2

我想創建一個簡單的宏(或者我以爲)來重命名工作簿中的單元格。該工作簿包含大約十幾張表。首先,我從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 

正如你所看到的,這是非常簡單的。我面臨的問題是,只有在手動轉到替換命令後將「內部:」選項更改爲「工作簿」時纔會運行。在那之後我可以整天運行宏,沒有問題。有沒有辦法在宏中將選項設置爲Workbook而不是Sheet?錄製宏時我這樣做了,但是由於某種原因它似乎沒有記錄那部分?

如果在其他地方報道過,請提前道歉。我搜索了很多次,但無法找到解決方案......這可能是由於我不瞭解要尋找什麼。

謝謝!

+0

也許在[本文](http://www.ozgrid.com/forum/showthread.php?t=118754)中的最後回覆將有所幫助。 – chuff

回答

1

而不是使用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 
+0

非常感謝chuff&d-stroyer。我能夠使用d-stroyer的代碼,它的工作非常好。感謝幫助! – Lazyeye