我一直在成功使用一个查找和替换过程,它传递了3个值Range(colRange),SearchString,ReplaceString,并且它一直正常工作。问题是现在我有更多要求。那些是现在:
所以我最近在短期内做的是将程序从findandreplace (ColRange, SearchString, ReplaceString)
更改为
findandreplace (FirstColRange, FirstSearchString, FirstReplaceString, SecondColRange, etc, etc)
然后我会通过findandreplace "A1:A", "test", test1, "C1:C", "blah1", "blah2", "", ""
在子例程中我添加了一些代码,如果不是SecondColRange""然后去做另一次搜索。
显然这是失败。
但是,我似乎无法通过最佳做法找到最佳方法。
所以我回到了绘图板并使用分隔符实现了一个带有分隔符的Dictionary对象。只需传递3个字符串就能再次工作。任何人都可以帮助我根据上述要求制作这种动态吗?
以下是我正在使用的代码。我知道它需要清理,但我只是首先尝试并运行功能。
Sub Cleanup2()
Set awb = ActiveWorkbook
With awb.Sheets("Sheet1")
Dim arrColOrder As Variant
Dim Counter As Integer, ndx As Integer
Dim dict As Object
Dim ItemKey As Variant
Set dict = CreateObject("Scripting.Dictionary")
Counter = 0
arrColOrder = Array("ColRange|A1:A", "SearchString|test", "ReplaceString|test1")
For ndx = LBound(arrColOrder) To UBound(arrColOrder)
v = Split(arrColOrder(ndx), "|")
dict.Add v(Counter), v(Counter + 1)
Next ndx
End With
WSFindAndReplaceAndUpdate "Sheet1", dict
Set dict = Nothing
End Sub
Sub WSFindAndReplaceAndUpdate(wSheet As String, dictionary As dictionary)
Set awb = ActiveWorkbook
Dim DsRangeCol As Range
Dim oSht As Worksheet
Dim LastRow As Long
Dim ItemKey
Set oSht = awb.Sheets(wSheet)
LastRow = oSht.Range("A" & Rows.Count).End(xlUp).Row
Set DsRangeCol = oSht.Range(dictionary.Item("ColRange") & LastRow).Find(dictionary.Item("SearchString"), LookAt:=xlPart)
If Not DsRangeCol Is Nothing Then
strFirstAddress = DsRangeCol.Address
Do
Set DsRangeCol = awb.Sheets(wSheet).Range(dictionary.Item("ColRange") & LastRow).FindNext(DsRangeCol)
DsRangeCol.Value = Replace(DsRangeCol.Value, dictionary.Item("SearchString"), dictionary.Item("ReplaceString"))
oSht.Range(DsRangeCol.Address) = DsRangeCol.Value
Loop Until DsRangeCol.Address = strFirstAddress
End If
End Sub
答案 0 :(得分:0)
您可以在任何参数之前使用Optional
关键字:
Function asdf(a As Integer, Optional b As String)
现在第一个参数是必需的,第二个参数是可选的。
您还可以为未传递参数时将使用的可选参数设置默认值:
Function asdf(a As Integer, Optional b As String = "test")
然后,您可以使用简单的if
检查参数是否已被修改If b <> "test" Then
在不传递b:
参数的情况下调用该函数asdf 12