Для каждого цикла не вносить изменения на всех листах? - PullRequest
0 голосов
/ 13 января 2019

Я изучаю Excel VBA через онлайн-курс.

Одно из упражнений требует, чтобы вы нашли и заменили текст в выбранной ячейке для всех листов. Вот моя попытка решения с использованием цикла For для каждого.

Sub Find_Replace_Selected_Value()
' Initialize Variables
Dim inputRange As Range
Dim searchString As String
Dim msgboxResp As VbMsgBoxResult
Dim msgboxRespAll As VbMsgBoxResult
Dim myWorkSheet As Worksheet

' Ask The user if they want the word replaced in all sheets.
msgboxRespAll = MsgBox("Would you like to apply changes to all sheets?", vbYesNoCancel, "Apply to All")

Select Case msgboxRespAll
    ' if the user only want to apply changes to current sheet.
    Case vbNo
        ' Ask User to select a range to search for.
        Set inputRange = Application.InputBox("Please select a range with a value to find and replace.", "Find", , , , , , 8)
        ' Ask User to input a value to replace with.
        searchString = InputBox("What would you like to replace " & inputRange.Value & " with?", "Replace")
        ' Perform Find and Replace
        Call Cells.Replace(inputRange.Value, searchString)
        ' Ask User to Repeat
        msgboxResp = MsgBox("Would you like to find and replace again?", vbYesNo, "Repeat")
        ' If yes, tell user that it's a future update.
        If msgboxResp = vbYes Then
        Call MsgBox("This functionality is scheduled for a later release.", vbOKOnly, "Not Available")
        End If
    ' if the user wants to apply changes to all sheets.
    Case vbYes
        ' Ask User to select a range to search for.
        Set inputRange = Application.InputBox("Please select a range with a value to find and replace.", "Find", , , , , , 8)
        ' Ask User to input a value to replace with.
        searchString = InputBox("What would you like to replace " & inputRange.Value & " with?", "Replace")
        ' Perform Find and Replace
        For Each myWorkSheet In Sheets()
            myWorkSheet.Activate
            Call Cells.Replace(inputRange.Value, searchString)
            Next

            ' Ask User to Repeat
            msgboxResp = MsgBox("Would you like to find and replace again?", vbYesNo, "Repeat")
            ' If yes, tell user that it's a future update.
            If msgboxResp = vbYes Then
            Call MsgBox("This functionality is scheduled for a later release.", vbOKOnly, "Not Available")
            End If


End Select


End Sub

Этот код заменяет значение только для одного листа.

Не могли бы вы помочь мне понять, почему этот метод не работает? Решение полностью отличается от того, что я не могу получить ответ от этого.

Ответы [ 2 ]

0 голосов
/ 13 января 2019

Запасная другая переменная

Для многолистовой версии объявите другую переменную для хранения начального значения диапазона ввода.

Код

Sub Find_Replace_Selected_Value()

    ' Initialize Variables
    Dim inputRange As Range
    Dim searchString As String
    Dim replaceString As String
    Dim msgboxResp As VbMsgBoxResult
    Dim msgboxRespAll As VbMsgBoxResult
    Dim myWorkSheet As Worksheet

    ' Ask The user if they want the word replaced in all sheets.
    msgboxRespAll = MsgBox("Would you like to apply changes to all sheets?", _
            vbYesNoCancel, "Apply to All")

    Select Case msgboxRespAll
        ' if the user only wants to apply changes to current sheet.
        Case vbNo
            ' Ask User to select a range to search in.
            Set inputRange = Application.InputBox("Please select a range " _
                    & "with a value to find and replace.", "Find", , , , , , 8)
            ' Ask User to input a value to replace with.
            replaceString = InputBox("What would you like to replace " _
                    & inputRange.Value & " with?", "Replace")
            ' Perform Find and Replace
            Cells.Replace inputRange.Value, replaceString
            ' Ask User to Repeat
            msgboxResp = MsgBox("Would you like to find and replace again?", _
                    vbYesNo, "Repeat")
            ' If yes, tell user that it's a future update.
            If msgboxResp = vbYes Then
                MsgBox "This functionality is scheduled for a later release.", _
                        vbOKOnly, "Not Available"
            End If
        ' if the user wants to apply changes to all sheets.
        Case vbYes
            ' Ask User to select a range to search in.
            Set inputRange = Application.InputBox("Please select a range " _
                    & "with a value to find and replace.", "Find", , , , , , 8)
            ' Ask User to input a value to replace with.
            replaceString = InputBox("What would you like to replace " _
                    & inputRange.Value & " with?", "Replace")
            ' Assign the value from inputRange to a variable.
            searchString = inputRange.Value
            ' Perform Find and Replace
            For Each myWorkSheet In Worksheets
                myWorkSheet.Cells.Replace searchString, replaceString
            Next
            ' Ask User to Repeat
            msgboxResp = MsgBox("Would you like to find and replace again?", _
                    vbYesNo, "Repeat")
            ' If yes, tell user that it's a future update.
            If msgboxResp = vbYes Then
                MsgBox "This functionality is scheduled for a later release.", _
                        vbOKOnly, "Not Available"
            End If
    End Select

End Sub
0 голосов
/ 13 января 2019

Проблема с переменной диапазона inputRange. Вы устанавливаете это как задание диапазона для листа active . Поэтому, когда он проходит по каждому листу, он ссылается на этот диапазон для каждого из листов. Таким образом, вы заменяете каждое значение на каждом листе одной и той же вещью.

Я бы изменил inputRange с переменной диапазона на простую строковую переменную. Таким образом, он будет статичным для каждого цикла. Так что просто измените inputRange на inputString и удалите ключевое слово "set" при получении значения из поля ввода.

Попробуйте это:

Sub Find_Replace_Selected_Value()
' Initialize Variables
Dim inputRange As Range
Dim inputString as String
Dim searchString As String
Dim msgboxResp As VbMsgBoxResult
Dim msgboxRespAll As VbMsgBoxResult
Dim myWorkSheet As Worksheet

' Ask The user if they want the word replaced in all sheets.
msgboxRespAll = MsgBox("Would you like to apply changes to all sheets?", vbYesNoCancel, "Apply to All")

Select Case msgboxRespAll
    ' if the user only want to apply changes to current sheet.
    Case vbNo
        ' Ask User to select a range to search for.
        Set inputRange = Application.InputBox("Please select a range with a value to find and replace.", "Find", , , , , , 8)
        ' Ask User to input a value to replace with.
        searchString = InputBox("What would you like to replace " & inputRange.Value & " with?", "Replace")
        ' Perform Find and Replace
        Call Cells.Replace(inputRange.Value, searchString)
        ' Ask User to Repeat
        msgboxResp = MsgBox("Would you like to find and replace again?", vbYesNo, "Repeat")
        ' If yes, tell user that it's a future update.
        If msgboxResp = vbYes Then
        Call MsgBox("This functionality is scheduled for a later release.", vbOKOnly, "Not Available")
        End If
    ' if the user wants to apply changes to all sheets.
    Case vbYes
        ' Ask User to select a range to search for.
        inputString = Application.InputBox("Please select a range with a value to find and replace.", "Find", , , , , , 8)
        ' Ask User to input a value to replace with.
        searchString = InputBox("What would you like to replace " & inputString & " with?", "Replace")
        ' Perform Find and Replace
        For Each myWorkSheet In Sheets()
            myWorkSheet.Activate
            Call Cells.Replace(inputString, searchString)
            Next

            ' Ask User to Repeat
            msgboxResp = MsgBox("Would you like to find and replace again?", vbYesNo, "Repeat")
            ' If yes, tell user that it's a future update.
            If msgboxResp = vbYes Then
            Call MsgBox("This functionality is scheduled for a later release.", vbOKOnly, "Not Available")
            End If


End Select


End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...