问题
I want to conditionally compile code in one VBAproject, with a condition that depends on some registry-entry. Is this somehow possible in VBA?
I know that there are some simple preprocessing possibilites in VBA, but I can not see if it is possible to somehow access the registry while preprocessing. Or Maybe some other possibility to check the registry before compiling.
Since I get a compile error because of some missing reference(and thus missing class object), I aim to check the registry before compiling.
P.s. I only want to read registry-entries.
As an example. How to reach debug.print in the following, i.e. avoiding compile errors.
sub sub1()
dim testobj as new nonexistingobject
sub2 testobj
debug.print "Arrived at this point"
end sub
sub sub2( byref testobj as nonexistingobject)
*do some stuff with testobj*
end sub
回答1:
Instead of using early binding (Dim obj as myObject
), use late bindings with CreateObject
. This way you will be able to handle the case where the object doesn't exists:
Sub test()
Dim obj As Object
On Error Resume Next
obj = CreateObject("myObject")
if Err then Exit Sub 'if the object wasn't found exit the function
on error goto 0 'set back the error handling to its previous state
'rest of the code
End Sub
回答2:
VBA does not directly provide access to the entire Windows Registry, but you can use a workaround.
Dim RegObj as Object
Set RegObj = CreateObject("WScript.Shell")
RegObj.RegDelete RegKeyString
RegObj.RegWrite RegKeyString
Str = RegObj.RegRead RegKeyString
Set RegObj = Nothing
If the RegKeyString is not found, it'll throw an error, so you need some OnError -> Key Doesn't Exist
kind of code.
Not sure of the preprocessing part, but you could run your code in the Workbook_Open
event handler to make sure this part runs before anything else.
回答3:
It is not feasible. All the symbols and conditions that are tested by VBA Directives are build from literals or expressions that include only operators (excepting the Is
operator, I think).
Function calls are not allowed when declaring directive symbols and conditions, and the only way to access registry in VBA is via API (like WScript.Shell
for example), which means function call.
Further reading: http://msdn.microsoft.com/en-us/library/tx6yas69.aspx
来源:https://stackoverflow.com/questions/24558164/vba-access-to-registry-while-preprocessing