Char type not defined - vba

Dim myChar As Char
throws Compile Error:
"User-defined type not defined"
What reference should I include to use Char type?

Char type does not exist in VBA, you should use String instead.
Dim myChar As String
Note that VBA is not the same as VB.NET. In VB.NET, you can use Char.
EDIT: Following Michał Krzych's suggestion, I'd use fixed-length string for this specific purpose.
Dim myChar As String * 1
Here is an excerpt from "VBA Developer's Handbook" by Ken Getz and Mike Gilbert:
"Dynamic strings require a bit more processing effort from VBA and are, accordingly, a bit slower to use."
...
"When working with a single character at a time, it makes sense to use
a fixed-length string declared to contain a single character. Because
you know you'll always have only a single character in the string,
you'll never need to trim off excess space. You get the benefits of a
fixed-length string without the extra overhead."
One caveat to this is that fixed string notation is NOT allowed in functions and subroutines;
Sub foo (char as string *1) 'not allowed
...
End Sub
So you would either need to use;
Sub foo (char as string) 'this will allow any string to pass
or
Sub foo (char as byte) 'the string would need to be converted to work
One thing to be careful of when using bytes is that there is no standard
whether a byte is unsigned or not. VBA uses unsigned bytes, which
is convenient in this situation.

I think it depends how you intend to use it:
Sub Test()
Dim strA As String, strB As Byte, strC As Integer, strD As Long
strA = "A"
strB = 65
strC = 75
strD = 90
Debug.Print Asc(strA) '65
Debug.Print Chr(strB) 'A
Debug.Print Chr(strC) 'K
Debug.Print Chr(strD) 'Z
End Sub

Related

Reading the PrtDevMode structure

I tried to read the Report.PrtDevMode property using the appropriate structures. If I do a Unicode conversion on the string I get closer, but the values still don't seem correct.
I expect to see intOrientation = 2 and strDeviceName = "C552 Color" and a paper size of 11x17.
I am testing on Windows 10 and Server 2008 with Microsoft Access 2010 (32-bit)
What I have Tried
A simplified copy and paste from the help file:
Private Type str_DEVMODE
RGB As String * 94
End Type
Private Type type_DEVMODE
strDeviceName As String * 32
intSpecVersion As Integer
intDriverVersion As Integer
intSize As Integer
intDriverExtra As Integer
lngFields As Long
intOrientation As Integer
intPaperSize As Integer
intPaperLength As Integer
intPaperWidth As Integer
intScale As Integer
intCopies As Integer
intDefaultSource As Integer
intPrintQuality As Integer
intColor As Integer
intDuplex As Integer
intResolution As Integer
intTTOption As Integer
intCollate As Integer
strFormName As String * 32
lngPad As Long
lngBits As Long
lngPW As Long
lngPH As Long
lngDFI As Long
lngDFr As Long
End Type
Public Sub CheckCustomPage()
Dim DevString As str_DEVMODE
Dim DM As type_DEVMODE
Dim strDevModeExtra As String
Dim rpt As Report
Dim intResponse As Integer
' Opens report in Design view.
DoCmd.OpenReport "rptNavigationPaneGroups", acDesign
Set rpt = Reports("rptNavigationPaneGroups")
If Not IsNull(rpt.PrtDevMode) Then
strDevModeExtra = rpt.PrtDevMode
' Gets current DEVMODE structure.
' (I added the StrConv function)
DevString.RGB = StrConv(strDevModeExtra, vbUnicode)
LSet DM = DevString
' List the device name.
If DM.strDeviceName <> rpt.Printer.DeviceName Then
Debug.Print "Found: '" & DM.strDeviceName & _
"' instead of '" & rpt.Printer.DeviceName & "'"
End If
End If
Set rpt = Nothing
End Sub
If I use the vbUnicode conversion, I get this output:
Found: 'C552 Color ”-é/ '
instead of 'C552 Color'
Without the conversion, the name is completely unreadable:
Found: '????? ?? A?A?????? ?'
instead of 'C552 Color
I reviewed numerous articles, documentation, and posts describing the usage of the .PrtDevMode property and associated structure.
I compared the structure type with examples in the help file, online documentation, and other sources, but I don't find any examples that involve Unicode conversion, which seems like it might be a piece of the puzzle.
I could use the .Printer object to retrieve many of these properties, but I understand that some settings like the Media Type are only available through the PrtDevMode structure (which is designed to mirror the Win32 SDK).
I could resort to using API calls to query the system printers, but this doesn't solve the problem of needing to write the structure back to the report print settings.
Using this structure would also help me to serialize this data in a readable format so that it can be stored in version control, and written back to the report after the database is rebuilt from source files (which is my ultimate goal).
Any non-null pointers in the right direction?
After further testing, I was able to get it working this morning. As I suspected, I was close on the Unicode conversion, but there were three important modifications that made the difference.
First, I needed to declare the two strings as byte arrays, not simply string buffers. While the string buffer works with the winspool.drv API calls, reading the Report.PrtDevMode property works better with a byte array.
Private Type type_DEVMODE
strDeviceName(1 To 32) As Byte ' <--- Byte array
'strDeviceName As String * 32
intSpecVersion As Integer
intDriverVersion As Integer
intSize As Integer
...
The second part was that the conversion from Unicode needs to be performed only on the string values, not the entire structure.
' Read the string values from DevMode structure
strDevice = NTrim(StrConv(dm.strDeviceName, vbUnicode))
strForm = NTrim(StrConv(dm.strFormName, vbUnicode))
Thirdly, the string is a null-terminated string, so it needs to be trimmed at the null character after the conversion from Unicode.
'---------------------------------------------------------------------------------------
' Procedure : NTrim
' Author : Adam Waller
' Date : 5/15/2020
' Purpose : Trim a null-terminated string.
'---------------------------------------------------------------------------------------
'
Public Function NTrim(strText) As String
Dim lngPos As Long
lngPos = InStr(1, strText, vbNullChar)
If lngPos > 0 Then
NTrim = Left$(strText, lngPos - 1)
Else
NTrim = strText
End If
End Function
With these three changes, I am now able to read the .PrtDevMode property with the expected values. Hopefully this will be helpful for someone else out there as well!
If you find that it works differently on your system, or have additional input, please feel free to leave a comment!

Equivalent of function String$() VB.Net?

I am migrating an application from VB6 to VB.Net, Which is using the String$() function.
My question is: Which is the "equivalent" of VB6 String$() in following Code?
Dim Symbol As String=""
Dim iRet As Long
iRet = GetLocaleInfo(LCID, LOCALE_SCURRENCY, lpLCDataVar, 0)
Symbol = String$(iRet, 0)
Note that String$() is the function which returns a repeating character string of the length specified:
Syntax:
String$(number, character)
number Length of the returned string.
character Required. Character
code specifying the character or string expression whose first
character is used to build the return string.
(reference)
If I will remove $, It will give me error that "String" is a Class and cannot used as an expression.
This String constructor is the correct way to create a String containing a specific number of a specific character, e.g.
Dim c = "0"c
Dim count = 10
Dim str As New String(c, count)
The equivalent to String$ (in older BASICs) is StrDup (VB.NET).
So, in your case:
Symbol = StrDup(iRet, Chr(0))
The code appears to be getting the currency symbol (and decimal separator) for a culture. It would be better to write it using .NET methods instead of the half-way route of using VB6 in .NET.
For example,
Imports System.Globalization
Module Module1
Sub Main()
Dim lcid = 2057
Dim ci As New CultureInfo(lcid)
Console.WriteLine(ci.EnglishName)
Console.WriteLine(ci.NumberFormat.CurrencySymbol)
Console.WriteLine(ci.NumberFormat.NumberDecimalSeparator)
Console.ReadLine()
End Sub
End Module
outputs
English (United Kingdom)
£
.
There is much more information in the documentation for the CultureInfo Class.

What is the difference between VBA.Str and VBA.Str$?

What is the difference between these two code lines
Debug.Print VBA.Str(123)
and
Debug.Print VBA.Str$(123)
Str$ and Str are identical except for at least 2 important differences:
If the usage of Str$ returns anything other than a String, you'll get an error:
Debug.Print Str(Null) 'Prints Null
Debug.Print Str$(Null) 'Throws Runtime Error 94 - Invalid use of Null
Str$ returns a String, whereas Str returns a Variant. In general, you should always prefer the strongly typed Str$ over Str
There are many other functions that use $-suffixes, like Left$, Mid$ and Space$.
If we look at Left$ (which is really just an alias for _stdcall _B_str_Left) and Left (which is really just an alias for _stdcall _B_var_Left), in the Type Library MIDL, we see that the input types matter too.
[entry(616), helpcontext(0x000f6ea1)]
BSTR _stdcall _B_str_Left(
[in] BSTR String,
[in] long Length);
[entry(617), helpcontext(0x000f653e)]
VARIANT _stdcall _B_var_Left(
[in] VARIANT* String,
[in] long Length);
You can actually use the underlying functions in code:
Debug.Print VBA.Strings.[_B_var_Left]("abc",1) 'Prints a
Debug.Print VBA.Strings.[_B_str_Left]("abc",1) 'Prints a
And to make matters more confusing, a function like Join (that does return a String, but which doesn't have a corresponding Join$ function, can actually be used with a $ suffix:
Debug.Print Join$(Array(1, 2, 3), ".") 'Prints 1.2.3
For further discussion, see my answer at Exactly what are these _B_var_Xxxxx and _B_str_Xxxxx members in the VBA COM libraries?
Str$ is identical to Str except for the declared type of its return value. i.e. Str returns a Variant, the Str$ returns a String.
Refer the msdn link

How to Xor a string with a password?

This is what I have so far.
Public Function XOREncDec(ByVal textToEncrypt As String) As String
Dim inSb As New StringBuilder(textToEncrypt)
Dim outSb As New StringBuilder(textToEncrypt.Length)
Dim c As Char
For i As Integer = 0 To textToEncrypt.Length - 1
c = inSb(i)
c = Chr(Asc(AscW(c)) Xor "password")
outSb.Append(c)
Next
Return outSb.ToString()
End Function
However I am getting an error here
c = Chr(Asc(AscW(c)) Xor "password")
"Conversion from string "password" to type 'Long' is not valid."
First, read the comments about better methods to protect strings.
Then, we can look at your code. You would xor characters with one character at a time from the password, not the whole password. You can use the loop variable with the mod operator to get the corresponding index in the password so it will repeat the characters in password along the length of the string.
Using Asc(Ascw(c)) means that you get the character code for the first character of the string representation of the character code for the character. For example the character A would give you the character code 65, that would implicitly be converted to the string "65" to get the character code for the character 6, which is 54. As you only use the first digit of the character code, it would not be possible to get the original string back.
You should use ony AscW to get the character code, and then ChrW to turn the adjusted character code back to a character. The Asc and Chr function doesn't support Unicode characters.
You don't need a StringBuilder for the input, you can access the characters directly from the string.
Public Function XOREncDec(ByVal textToScramble As String) As String
Dim builder As New StringBuilder(textToScramble.Length)
Dim password As String = "password"
Dim c As Char
For i As Integer = 0 To textToScramble.Length - 1
Dim pos As Integer = i mod password.Length
c = textToScramble(i)
c = ChrW(AscW(c) Xor AscW(password(pos)))
builder.Append(c)
Next
Return builder.ToString()
End Function
Note that I renamed the parameter from textToEncrypt to textToScramble, as this simple encoding can't be called encryption in any modern sense of the word.
A word of caution also, the string that is the result of encoding will often contain character codes that doesn't correspond to real characters. It works as long as you decode the same string object, but if you for example write the string to a file and then try to read it back, it will most likely get corrupted. To get data that would survive any kind of storage or communication, you would encode the string into bytes, scramble the bytes, and then create a string value from the bytes using for example base64 encoding.

Hidden features of VBA

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Which features of the VBA language are either poorly documented, or simply not often used?
This trick only works in Access VBA, Excel and others won't allow it. But you can make a Standard Module hidden from the object browser by prefixing the Module name with an underscore. The module will then only be visible if you change the object browser to show hidden objects.
This trick works with Enums in all vb6 based version of VBA. You can create a hidden member of an Enum by encasing it's name in brackets, then prefixing it with an underscore. Example:
Public Enum MyEnum
meDefault = 0
meThing1 = 1
meThing2 = 2
meThing3 = 3
[_Min] = meDefault
[_Max] = meThing3
End Enum
Public Function IsValidOption(ByVal myOption As MyEnum) As Boolean
If myOption >= MyEnum.[_Min] Then IsValidOption myOption <= MyEnum.[_Max]
End Function
In Excel-VBA you can reference cells by enclosing them in brackets, the brackets also function as an evaluate command allowing you to evaluate formula syntax:
Public Sub Example()
[A1] = "Foo"
MsgBox [VLOOKUP(A1,A1,1,0)]
End Sub
Also you can pass around raw data without using MemCopy (RtlMoveMemory) by combining LSet with User Defined Types of the same size:
Public Sub Example()
Dim b() As Byte
b = LongToByteArray(8675309)
MsgBox b(1)
End Sub
Private Function LongToByteArray(ByVal value As Long) As Byte()
Dim tl As TypedLong
Dim bl As ByteLong
tl.value = value
LSet bl = tl
LongToByteArray = bl.value
End Function
Octal & Hex Literals are actually unsigned types, these will both output -32768:
Public Sub Example()
Debug.Print &H8000
Debug.Print &O100000
End Sub
As mentioned, passing a variable inside parenthesis causes it to be passed ByVal:
Sub PredictTheOutput()
Dim i&, j&, k&
i = 10: j = i: k = i
MySub (i)
MySub j
MySub k + 20
MsgBox Join(Array(i, j, k), vbNewLine), vbQuestion, "Did You Get It Right?"
End Sub
Public Sub MySub(ByRef foo As Long)
foo = 5
End Sub
You can assign a string directly into a byte array and vice-versa:
Public Sub Example()
Dim myString As String
Dim myBytArr() As Byte
myBytArr = "I am a string."
myString = myBytArr
MsgBox myString
End Sub
"Mid" is also an operator. Using it you overwrite specific portions of strings without VBA's notoriously slow string concatenation:
Public Sub Example1()
''// This takes about 47% of time Example2 does:
Dim myString As String
myString = "I liek pie."
Mid(myString, 5, 2) = "ke"
Mid(myString, 11, 1) = "!"
MsgBox myString
End Sub
Public Sub Example2()
Dim myString As String
myString = "I liek pie."
myString = "I li" & "ke" & " pie" & "!"
MsgBox myString
End Sub
There is an important but almost always missed feature of the Mid() statement. That is where Mid() appears on the left hand side of an assignment as opposed to the Mid() function that appears in the right hand side or in an expression.
The rule is that if the if the target string is not a string literal, and this is the only reference to the target string, and the length of segment being inserted matches the length of the segment being replaced, then the string will be treated as mutable for the operation.
What does that mean? It means that if your building up a large report or a huge list of strings into a single string value, then exploiting this will make your string processing much faster.
Here is a simple class that benefits from this. It gives your VBA the same StringBuilder capability that .Net has.
' Class: StringBuilder
Option Explicit
Private Const initialLength As Long = 32
Private totalLength As Long ' Length of the buffer
Private curLength As Long ' Length of the string value within the buffer
Private buffer As String ' The buffer
Private Sub Class_Initialize()
' We set the buffer up to it's initial size and the string value ""
totalLength = initialLength
buffer = Space(totalLength)
curLength = 0
End Sub
Public Sub Append(Text As String)
Dim incLen As Long ' The length that the value will be increased by
Dim newLen As Long ' The length of the value after being appended
incLen = Len(Text)
newLen = curLength + incLen
' Will the new value fit in the remaining free space within the current buffer
If newLen <= totalLength Then
' Buffer has room so just insert the new value
Mid(buffer, curLength + 1, incLen) = Text
Else
' Buffer does not have enough room so
' first calculate the new buffer size by doubling until its big enough
' then build the new buffer
While totalLength < newLen
totalLength = totalLength + totalLength
Wend
buffer = Left(buffer, curLength) & Text & Space(totalLength - newLen)
End If
curLength = newLen
End Sub
Public Property Get Length() As Integer
Length = curLength
End Property
Public Property Get Text() As String
Text = Left(buffer, curLength)
End Property
Public Sub Clear()
totalLength = initialLength
buffer = Space(totalLength)
curLength = 0
End Sub
And here is an example on how to use it:
Dim i As Long
Dim sb As StringBuilder
Dim result As String
Set sb = New StringBuilder
For i = 1 to 100000
sb.Append CStr( i)
Next i
result = sb.Text
VBA itself seems to be a hidden feature. Folks I know who've used Office products for years have no idea it's even a part of the suite.
I've posted this on multiple questions here, but the Object Browser is my secret weapon. If I need to ninja code something real quick, but am not familiar with the dll's, Object Browser saves my life. It makes it much easier to learn the class structures than MSDN.
The Locals Window is great for debugging as well. Put a pause in your code and it will show you all the variables, their names, and their current values and types within the current namespace.
And who could forget our good friend Immediate Window? Not only is it great for Debug.Print standard output, but you can enter in commands into it as well. Need to know what VariableX is?
?VariableX
Need to know what color that cell is?
?Application.ActiveCell.Interior.Color
In fact all those windows are great tools to be productive with VBA.
It's not a feature, but a thing I have seen wrong so many times in VBA (and VB6): Parenthesis added on method calls where it will change semantics:
Sub Foo()
Dim str As String
str = "Hello"
Bar (str)
Debug.Print str 'prints "Hello" because str is evaluated and a copy is passed
Bar str 'or Call Bar(str)
Debug.Print str 'prints "Hello World"
End Sub
Sub Bar(ByRef param As String)
param = param + " World"
End Sub
Hidden Features
Although it is "Basic", you can use OOP - classes and objects
You can make API calls
Possibly the least documented features in VBA are those you can only expose by selecting "Show Hidden Members" on the VBA Object Browser. Hidden members are those functions that are in VBA, but are unsupported. You can use them, but microsoft might eliminate them at any time. None of them has any documentation provided, but you can find some on the web. Possibly the most talked about of these hidden features provides access to pointers in VBA. For a decent writeup, check out; Not So Lightweight - Shlwapi.dll
Documented, but perhaps more obscure (in excel anyways) is using ExecuteExcel4Macro to access a hidden global namespace that belongs to the entire Excel application instance as opposed to a specific workbook.
You can implement interfaces with the Implements keyword.
Dictionaries. VBA is practically worthless without them!
Reference the Microsoft Scripting Runtime, use Scripting.Dictionary for any sufficiently complicated task, and live happily ever after.
The Scripting Runtime also gives you the FileSystemObject, which also comes highly recommended.
Start here, then dig around a bit...
http://msdn.microsoft.com/en-us/library/aa164509%28office.10%29.aspx
Typing VBA. will bring up an intellisense listing of all the built-in functions and constants.
With a little work, you can iterate over custom collections like this:
' Write some text in Word first.'
Sub test()
Dim c As New clsMyCollection
c.AddItems ActiveDocument.Characters(1), _
ActiveDocument.Characters(2), _
ActiveDocument.Characters(3), _
ActiveDocument.Characters(4)
Dim el As Range
For Each el In c
Debug.Print el.Text
Next
Set c = Nothing
End Sub
Your custom collection code (in a class called clsMyCollection):
Option Explicit
Dim m_myCollection As Collection
Public Property Get NewEnum() As IUnknown
' This property allows you to enumerate
' this collection with the For...Each syntax
' Put the following line in the exported module
' file (.cls)!'
'Attribute NewEnum.VB_UserMemId = -4
Set NewEnum = m_myCollection.[_NewEnum]
End Property
Public Sub AddItems(ParamArray items() As Variant)
Dim i As Variant
On Error Resume Next
For Each i In items
m_myCollection.Add i
Next
On Error GoTo 0
End Sub
Private Sub Class_Initialize()
Set m_myCollection = New Collection
End Sub
Save 4 whole keystrokes by typing debug.? xxx instead of debug.print xxx.
Crash it by adding: enum foo: me=0: end enum to the top of a module containing any other code.
Support for localized versions, which (at least in the previous century) supported expressions using localized values. Like Pravda for True and Fałszywy (not too sure, but at least it did have the funny L) for False in Polish... Actually the English version would be able to read macros in any language, and convert on the fly. Other localized versions would not handle that though.
FAIL.
The VBE (Visual Basic Extensibility) object model is a lesser known and/or under-utilized feature. It lets you write VBA code to manipulate VBA code, modules and projects. I once wrote an Excel project that would assemble other Excel projects from a group of module files.
The object model also works from VBScript and HTAs. I wrote an HTA at one time to help me keep track of a large number of Word, Excel and Access projects. Many of the projects would use common code modules, and it was easy for modules to "grow" in one system and then need to be migrated to other systems. My HTA would allow me to export all modules in a project, compare them to versions in a common folder and merge updated routines (using BeyondCompare), then reimport the updated modules.
The VBE object model works slightly differently between Word, Excel and Access, and unfortunately doesn't work with Outlook at all, but still provides a great capability for managing code.
IsDate("13.50") returns True but IsDate("12.25.2010") returns False
This is because IsDate could be more precisely named IsDateTime. And because the period (.) is treated as a time separator and not a date separator. See here for a full explanation.
VBA supports bitwise operators for comparing the binary digits (bits) of two values. For example, the expression 4 And 7 evaluates the bit values of 4 (0100) and 7 (0111) and returns 4 (the bit that is on in both numbers.) Similarly the expression 4 Or 8 evaluates the bit values in 4 (0100) and 8 (1000) and returns 12 (1100), i.e. the bits where either one is true.
Unfortunately, the bitwise operators have the same names at the logical comparison operators: And, Eqv, Imp, Not, Or, and Xor. This can lead to ambiguities, and even contradictory results.
As an example, open the Immediate Window (Ctrl+G) and enter:
? (2 And 4)
This returns zero, since there are no bits in common between 2 (0010) and 4 (0100).
Deftype Statements
This feature exists presumably for backwards-compatibility. Or to write hopelessly obfuscated spaghetti code. Your pick.