我在excel中编写vba代码,我是新手:)
请帮我解决以下问题:
A1
=B1*C1*D1
中有一个公式
B1
,C1
和D1
各自有值(即3,2,1)我希望将公式作为字符串 - 即=3*2*1
- 使用VBA
答案 0 :(得分:2)
您可以使用
Evaluate
所有这些字符串部分它可能需要对复杂的字符串进行处理,但它是一个好的开始
针对更复杂的匹配进行了更新
<强>码强>
Sub ParseEm()
Dim strIn As String
Dim strNew As String
Dim strCon As String
Dim lngCnt As Long
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
strCon = "|"
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "[^=/+/\/-/*\^]+"
.Global = True
strIn = [a1].Formula
If .test(strIn) Then
Set objRegMC = .Execute(strIn)
For Each objRegM In objRegMC
strNew = Evaluate(CStr(objRegM))
If objRegM.Length >= Len(strNew) Then
Mid$(strIn, objRegM.firstindex + 1 + lngCnt, objRegM.Length) = strNew & Application.Rept(strCon, objRegM.Length - Len(strNew))
Else
strIn = Left$(strIn, objRegM.firstindex + lngCnt) & strNew & Right$(strIn, Len(strIn) - objRegM.firstindex - objRegM.Length - lngCnt - 1)
lngCnt = lngCnt + Len(strNew) - objRegM.Length
End If
Next
strIn = Replace(strIn, strCon, vbNullString)
MsgBox strIn
Else
MsgBox "sorry, no matches"
End If
End With
End Sub
答案 1 :(得分:0)
我知道的唯一方法是使用Precedents
功能:
Sub GetFormulaAsString()
Dim var As Range, temp As String, formulaAsString As String
temp = "="
For Each var In Range("A1").Precedents
temp = temp & var & "*"
Next var
formulaAsString = VBA.Left$(temp, Len(temp) - 1) // "=3*2*1"
End Sub
答案 2 :(得分:0)
想法是用'值'替换.Formula属性中的单元格引用。唯一的麻烦是使用$ sign in formula,因此添加了cA和rA循环。
Sub GetFormulaAsString()
Dim var As Range
Dim temp As String
Dim R As Range
Dim v As Variant
Dim cA As Integer
Dim rA As Integer
Dim cellname As String
Set R = Range("A1")
temp = R.Formula
Debug.Print temp
For Each var In R.DirectPrecedents
v = var.Value
For cA = 1 To 0 Step -1
For rA = 1 To 0 Step -1
cellname = var.Address(cA, rA)
temp = Replace(temp, cellname, v)
Next rA
Next cA
Next var
Debug.Print temp
msgbox temp
End Sub
答案 3 :(得分:0)
我已经完成了这个问题,伪是:
查找字符串a1 b1 c1
在单元格a1
="="&b1&"*"&c1&"*"&d1
获取a1