excel 如何从字符串(formulaR1C1)中提取值(username),以在整个文档中的1000多个公式中进行替换

cbwuti44  于 2023-03-13  发布在  其他
关注(0)|答案(2)|浏览(138)

我有一个嵌入了1000多个公式的文档,所以我提取了Environ(“用户名”),并从R1C1公式中提取“C:\Users[用户名]\OneDrive\”中所有公式的当前用户名,然后替换为新的Environ用户名。
我开发的公式是:

MID(B3,FIND(CHAR(1),SUBSTITUTE(B3,"\",CHAR(1),2))+1,FIND(CHAR(1),SUBSTITUTE(B3,"\",CHAR(1),3))-FIND(CHAR(1),SUBSTITUTE(B3,"\",CHAR(1),2))-1)

B3应为:

Worksheets(1).Range("L2").FormulaR1C1

但该公式只能在Excel中使用,而不能在VBA环境下使用,我尝试了求值方法,但没有成功
下面是代码:

Dim EnvUser As String
EnvUser = Environ("username")

Dim User As String
        
User = Worksheets(1).Range("L2").FormulaR1C1

User = Application.Evaluate("Mid(User, Find(CHAR(1), Substitute(User, " \ ", CHAR(1), 2)) + 1, Find(CHAR(1), Substitute(User, " \ ", CHAR(1), 3)) - Find(CHAR(1), Substitute(User, " \ ", CHAR(1), 2)) - 1)")
MsgBox User
qkf9rpyu

qkf9rpyu1#

使用正则表达式进行模式匹配和替换。

Option Explicit

Sub ChgUser()

    Dim regex, f As String
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Global = True
        .MultiLine = False
        .IgnoreCase = True
        .Pattern = "(.*Users\\)([^\\]+)(\\OneDrive.*)"
    End With

    Dim cell As Range, n As Long, NewUser As String
    NewUser = Environ("username")

    For Each cell In Sheets("Sheet1").UsedRange
    
        f = cell.Formula2R1C1 '"C:\Users\username\OneDrive\"
        If regex.Test(f) Then
           f = regex.Replace(f, "$1" & NewUser & "$3")
           'Debug.Print cell.Address, f
           cell.Formula2R1C1 = f
           n = n + 1
        End If
        
    Next
    MsgBox n & " cells updated.", vbInformation
End Sub
tcomlyy6

tcomlyy62#

更改OneDrive路径中的用户名

Sub ChangeUser()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containg this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(1)
    Dim cell As Range: Set cell = ws.Range("L2")
    
    Dim CellString As String: CellString = cell.FormulaR1C1 ' .Formula
    
    Dim lp As Long: lp = InStr(1, CellString, "C:\Users\", vbTextCompare)
    Dim rp As Long
    rp = InStr(1, CellString, "OneDrive", vbTextCompare) + Len("OneDrive")
    
    Dim OldPath As String: OldPath = Mid(CellString, lp, rp - lp)
    
    MsgBox OldPath

    ' e.g.:
    Dim NewPath As String: NewPath = Environ("OneDrive")
    'ws.UsedRange.Replace OldPath, NewPath, xlPart
    
End Sub

相关问题