VBA序列化模块到JSON



我有一个VBA项目,我正在转换为c#。我需要能够运行单元测试来验证转换后的c#代码。所有原始应用程序的数据都存储在全局变量的单个模块中,序列化这个模块将非常有用,这样我就可以在单元测试中从中获取子例程输入和输出。

我读了其他问题,发现了这个github项目:

https://github.com/VBA-tools/VBA-JSON

不幸的是,你必须传递一个对象到它的"ConvertToJson"函数和模块没有我可以传入的引用。

这个库有序列化模块而不是类模块的方法吗?

是否有办法从模块创建对象引用?

谢谢!

您可以尝试将模块转换为带有PredeclaredId的类。不需要新建对象,只需在方法调用前加上类名。为了避免导出模块的麻烦,将predeclaredId设置为true并重新导入,您可以安装免费的神奇的Rubberduck插件。

没有一种优雅的方式来序列化VBA标准模块,但我找到了一种使用可扩展性库来实现它的方法。(类似于反射)。请原谅附件代码的初步状态;它还没有写入序列化格式,它只是检索标准模块中的所有双精度,并打印它们的值,只要模块只包含变量声明。虽然这不是一个完整的或健壮的序列化代码,但它具有难以用标准模块完成的部分。一旦我写了一个更完整的例程,我将更新。

Public Sub Serialize()
Dim code As String
Dim splitCode As Variant
Dim variableName As String
Dim i As Integer
Dim count As Integer
Dim Project As VBProject
Dim module As CodeModule
Dim value As Variant
Dim nextClass As VBComponent

Set Project = ThisWorkbook.VBProject
Set module = Project.VBComponents("TheModule").CodeModule
i = 1
Do While i <= module.CountOfLines

'Get the next line of the Module of interest
code = module.Lines(i, 1)

'Look for any variable types we care about
If InStr(code, "Double") <> 0 Then

splitCode = Split(code)
variableName = splitCode(1)

Set nextClass = Project.VBComponents.Add(vbext_ct_StdModule)
nextClass.Name = "aaaTMP"

'Inject the Function we need
nextClass.CodeModule.InsertLines 1, "Public Function GetValue() As Variant"
nextClass.CodeModule.InsertLines 2, "GetValue = " & variableName
nextClass.CodeModule.InsertLines 3, "End Function"

value = Application.Run("GetValue")

MsgBox variableName & ": " & value
Project.VBComponents.Remove nextClass

End If

i = i + 1
Loop
End Sub

最新更新