This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModuleParser.cs
56 lines (47 loc) · 1.59 KB
/
ModuleParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using Microsoft.Vbe.Interop;
using Microsoft.VisualBasic;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
namespace VBA_Export
{
public class ModuleParser
{
public VBCodeProvider Provider { get; } = new VBCodeProvider();
public CodeModule Module { get; private set; }
public string Name { get => Module.Name; }
public string FileName { get => $"{Name}.vb"; }
public string DesignerFileName { get => $"{Name}.Designer.vb"; }
public bool IsForm { get; set; }
public ModuleParser(CodeModule module)
{
this.Module = module;
}
public override string ToString()
{
if (Module.CountOfLines == 0)
return null;
string code = Environment.NewLine + Module.Lines[1, Module.CountOfLines] + Environment.NewLine;
string output = $"Module {Name}" + code + "End Module";
if (IsForm)
output = $"Public Class {Name}" + code + "End Class";
// Try to format code
try
{
CodeCompileUnit unit;
using (var reader = new StringReader(output))
{
unit = Provider.Parse(reader);
}
using (var writer = new StringWriter())
{
Provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
output = writer.ToString();
}
}
catch { }
return output;
}
}
}