Обновление внизу с учетом комментария Майкла относительно лучшего подхода ко многим заменам шаблонов
Если вы запишете простой макрос, используя ручные Replace
параметры из меню Excel, вы получите код, который вы можете привести в порядок до этого
- Первый вариант обновит ячейку в
ActiveSheet
, чем содержит "I am A1"
до "I am System"
- совпадение строки части
- Второй вариант будет обновлять только ячейки в
ActiveSheet
, которые содержат только от "A1"
до "Sytem"
, т. е. совпадение всей строки ячейки
код
Sub UpdatePartial()
With ActiveSheet.UsedRange
.Replace "A1", "System", xlPart
.Replace "A2", "System", xlPart
.Replace "A3", "System", xlPart
.Replace "B1", "ACC", xlPart
.Replace "B2", "ACC", xlPart
End With
End Sub
Sub UpdateWhole()
With ActiveSheet.UsedRange
.Replace "A1", "System", xlWhole
.Replace "A2", "System", xlWhole
.Replace "A3", "System", xlWhole
.Replace "B1", "ACC", xlWhole
.Replace "B2", "ACC", xlWhole
End With
End Sub
Обновить
Код ниже
- Использует базовый
Timer
для сравнения замены всех частичных строк в диапазоне от A1-A99
до B1-B99
- The two methods are
- The
Replace
method above called 198 times (ie 2*99) in a loop
- Комбинация массивов
RegExp
\ variant
В моем тестировании второй метод быстрее для 198 замен в диапазоне 1 000 000 ячеек.
Меньшее количество замен улучшит относительную скорость по отношению к Replace
. Больше к RegExp
Больше ячеек также улучшит относительную скорость к Replace
. Меньше к RegExp
Я не стал пробовать метод Find
с последующим анализом строк. В качестве решения гибридного типа (найти, затем разобрать, но не будет конкурировать с одной заменой или разбором)
Таймер
Sub MainCaller()
Dim dbTime As Double
Dim lngCnt As Long
dbTime = Timer()
For lngCnt = 1 To 99
Call UpdatePartial("A" & lngCnt, "System")
Call UpdatePartial("B" & lngCnt, "System")
Next lngCnt
Debug.Print Timer() - dbTime
dbTime = Timer()
Call RegexReplace("(A|B)[1-99]", "System")
Debug.Print Timer() - dbTime
End Sub
1) Заменить подпрограмму
Sub UpdatePartial(StrIn As String, StrOut As String)
ActiveSheet.UsedRange.Replace StrIn, StrOut, xlPart
End Sub
2) Регулярное выражение – вложенный вариант массива
Sub RegexReplace(StrIn As String, StrOut As String)
Dim rng1 As Range
Dim rngArea As Range
Dim lngRow As Long
Dim lngCol As Long
Dim lngCalc As Long
Dim objReg As Object
Dim X()
'On Error Resume Next
'Set rng1 = Application.InputBox("Select range for the replacement of leading zeros", "User select", Selection.Address, , , , , 8)
'If rng1 Is Nothing Then Exit Sub
'On Error GoTo 0
ActiveSheet.UsedRange
Set rng1 = ActiveSheet.UsedRange
'See Patrick Matthews excellent article on using Regular Expressions with VBA
Set objReg = CreateObject("vbscript.regexp")
With objReg
.Pattern = StrIn
.ignorecase = False
.Global = True
End With
'Speed up the code by turning off screenupdating and setting calculation to manual
'Disable any code events that may occur when writing to cells
With Application
lngCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
.EnableEvents = False
End With
'Test each area in the user selected range
'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on
For Each rngArea In rng1.Areas
'The most common outcome is used for the True outcome to optimise code speed
If rngArea.Cells.Count > 1 Then
'If there is more than once cell then set the variant array to the dimensions of the range area
'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks
X = rngArea.Value2
For lngRow = 1 To rngArea.Rows.Count
For lngCol = 1 To rngArea.Columns.Count
'replace the leading zeroes
X(lngRow, lngCol) = objReg.Replace(X(lngRow, lngCol), StrOut)
Next lngCol
Next lngRow
'Dump the updated array back over the initial range
rngArea.Value2 = X
Else
'caters for a single cell range area. No variant array required
rngArea.Value = objReg.Replace(rngArea.Value, StrOut)
End If
Next rngArea
'cleanup the Application settings
With Application
.ScreenUpdating = True
.Calculation = lngCalc
.EnableEvents = True
End With
Set objReg = Nothing
End Sub
person
brettdj
schedule
07.11.2012