VBA脚本复制一个值,replace正斜杠和合并,而在Excel中最后添加一个特定的值
我有一个Excel工作表,其中包含如下所示的值:
BL/ER/D11/fmp000005578/0001 BL/ER/D11/fmp000005578/0002 BL/ER/D11/fmp000005578/0002
我需要他们看起来像这样:
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001_1.jpg /data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0002_1.jpg /data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0003_1.jpg
模式很多是:
- 从最后删除数字。 (
BL/ER/D11/fmp000005578/
) - 复制值,用下划线replace该特定值的正斜杠。 (
BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_
) - 添加数字。 (
BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001
) - 添加
_1.jpg
到最后。 (BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001_1.jpg
) - 将
/data01/
添加到前面。 (/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001_1.jpg
)
对于同一列中的每个值,都需要重复此过程。
一个电子表格中有多个工作表/选项卡,所以不pipe怎样,如果可能的话,macros应该可以在多个工作表/选项卡上执行。
我现在的代码是:
Sub FileDirectoryRegExTest() Dim regEx As New RegExp Dim strPattern As String Dim strInput As String Dim strReplace As String Dim Myrange As Range Set Myrange = ActiveSheet.Range("A2:A4620") For Each c In Myrange strPattern = "([AZ]{2}\/[AZ]{2}\/[AZ][0-9]{2}\/[az]{3}[0-9]{9}\/)([0-9]{4})" If strPattern <> "" Then strInput = c.Value strReplace = "$1" With regEx .Global = True .MultiLine = True .IgnoreCase = False .Pattern = strPattern End With If regEx.test(strInput) Then c.Offset(0, 1) = regEx.Replace(strInput, "$2") Else c.Offset(0, 1) = "" End If End If Next End Sub
我已经使用这个代码以前的函数,但我不太确定是否可以重新使用此代码来执行这些特定的function。
如果你可以编辑这个脚本或创build一个执行这个function的新脚本,那将是非常棒的,谢谢!
谢谢!
Aydan H.
Sub FileDirectoryRegExTest() For Each sht In Sheets lastRow = sht.Range("A65000").End(xlUp).Row Set Myrange = sht.Range("A2:A" & lastRow) For Each c In Myrange c.Offset(0, 1) = "/data01/" & Left(c, Len(c) - 4) & Replace(Left(c, Len(c) - 4), "/", "_") & Right(c, 4) & "_1.jpg" Next c Next sht End Sub
你真的需要使用正则expression式吗?
如何简单的一点代码:
"/data01/" & Mid(c.Value, 1, Len(c.Value) - 4) & Replace(c.Value, "/", "_") & "_1.jpg"
不知道_1
之前的最后一位数字是否应该增加? 如果他们这样做,你可以只在string中添加一个计数器
这可以做到没有正则expression式,我喜欢很多,但他们很慢,看到这个代码:
Function something(inString As String) As String Dim lastSlash As Integer Dim firstPart As String, lastPart As String lastSlash = Len(inString) - InStr(1, StrReverse(inString), "/") firstPart = Mid(inString, 1, lastSlash) lastPart = Mid(inString, lastSlash + 2, 9999) something = firstPart & "/" & Replace(firstPart, "/", "_") & "_" & lastPart & "_1.jpg" End Function
你甚至可以用它作为你的工作表上的公式。