提问人:steveOw 提问时间:10/17/2023 最后编辑:steveOw 更新时间:11/17/2023 访问量:144
将字符串内 VB6 字符串变量的名称替换为该字符串变量的内容?
Replace the name of a VB6 string variable inside a string by the contents of that string variable?
问:
tl;dr 跳到下面的问题。
上下文
在我的代数数学程序中,公式可以输入以下形式(作为 VB6 代码行)。(字符串中的空格将被忽略):
formula1$ = "SUM (a,b,c)"
formula2$ = "SUM (x,y,z)"
formula3$ = "PRODUCT (a,x)"
formula4$ = "PRODUCT ((SUM (a,b,c)) , (SUM (x,y,z))) "
formula5$ = "PRODUCT (" + formula1$ +") , (" + formula2$ +")"
(我知道对用户来说有点繁琐,但在处理长公式时平衡得更好)。
然后,的内容与 的内容相同。formula5$
formula4$
有一个变量很有用,该变量在检查/打印时描述了以下规范:formula5_descr$
formula5$
debug.print formula5_descr$ ' --> "PRODUCT (" + formula1$ +") , (" + formula1$ +")"
的代码可以手动生成。但是,这很难做到,不能指望用户去做。formula5_descr$
我想让用户输入更简单的代码形式,例如:
formula5$ = "PRODUCT (formula1$ ) , ( formula2$ )"
然后可以修改程序以解析公式字符串并替换任何字符串引用(即 和 ) 相关字符串的内容(即 和 )。"PRODUCT (formula1$ ) , ( formula2$ )"
formula1$
formula2$
SUM (a,b,c)
SUM (x,y,z)
问题
问题来了 - 如何在 VB6 中用该字符串变量的内容替换字符串内字符串变量的名称?
(用户 Joel Coehoorn 指出,在较新的语言中,如 VB14+、C#、javascript 等,有一个称为字符串插值的过程。
理想情况下,将有一个函数,以便:REVEAL()
REVEAL("formula1$") --> "SUM (a,b,c)"
注意MS Access 中存在针对 VBA 的解决方案这一事实并不意味着该解决方案会自动适用于 VB6。它们是相似但不同的语言,VB6 的安装不一定安装与 MS Access 相同的组件。
答:
使用字典按键存储公式。 之后,只需将公式名称替换为它们的值即可。
Option Explicit
Dim dictFormulas As New Dictionary
Private Sub Command1_Click()
ReadLines Text1.Text
PrintFormulas
End Sub
Private Sub ReadLines(strText As Variant)
Dim i As Long
Dim strLines() As String
strLines = Split(strText, vbNewLine)
For i = LBound(strLines) To UBound(strLines)
AddFormula strLines(i)
Next
End Sub
Private Sub AddFormula(strLine As String)
Dim strFormulaName As String
Dim strFormulaValue As String
Dim strItem As Variant
Dim strFormulaVect() As String
strFormulaVect = Split(strLine, "=")
strFormulaName = Trim(strFormulaVect(0))
strFormulaValue = Trim(strFormulaVect(1))
For Each strItem In dictFormulas.Keys
strFormulaValue = Replace(strFormulaValue, strItem, CStr(dictFormulas(strItem)))
Next
dictFormulas.Add strFormulaName, strFormulaValue
End Sub
Private Sub PrintFormulas()
Dim strItem As Variant
For Each strItem In dictFormulas.Keys
Debug.Print strItem & "=" & CStr(dictFormulas(strItem))
Next
End Sub
字典是脚本库 (SCRRUN.DLL) 的一部分Microsoft必须作为引用添加到 Project > 引用中
评论
Compile error: User-defined type not defined
Set dictFormulas = CreateObject("Scripting.Dictionary")
Compile error: User-defined type not defined
你要做的叫做字符串插值,vb6 已经足够老了,对这个功能没有任何支持。您需要执行其他操作,例如使用字典将键 like 映射到值 ,然后手动将键替换为最终字符串中的值。formula1$
SUM (a,b,c)
评论
CallByName
CallByName
CallByName()