MS Access VBA - how to read utf8 text independantly from Windows system locale - ms-access

I have a MySQL table with a text field. It contains a hyperlink, and it is encoded in utf8 (utf8-unicode-ci collation). I want to open the hyperlink programmatically from VBA.
The text field may contain characters like "őűö", which are not present in western European codepage (1252), but available in central European (1250).
My first attempt was to run a pass-trough query, read the field value into a VBA string, and open it with Application.Followhyperlink. It works, when windows system locale - default codepage for non-Unicode compatible applications in regional settings - is Hungarian (uses codepage 1250), and fails, when the system locale is German (uses codepage 1252). The VBA string contains a value converted to the codepage specified by the system locale. So "C:\tükörtűrő" will be read as "C:\tukorturo".
I am not allowed to fix the system locale on 100+ computers. So, how to do it right?
Edit:
Lessons learned:
Debug.Print doesn't support Unicode – as stated by Erik von Asmuth. The displayed text in the debug window is misleading.
Application.FollowHyperlink can handle Unicode.
The real problem was a link health check right before opening the link, where I have used the built in GetAttr(), which depends on system locale settings. I have replaced it with GetFileAttributesW(), everything seems to work now. Some credit goes here to Bonnie West. (https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=74264&lngWId=1)

VBA and Access use UTF-16 internally, not the system codepage, so this shouldn't be a problem at all. Pass-through queries should just work. However:
You need to use the MySQL Unicode driver, not the MySQL ANSI driver
Not all VBA functions support unicode characters. For example,
MsgBox is ANSI only, and will cast unavailable characters to
either questionmarks or the closest equivalent ANSI character.
The VBA code itself is not unicode. You can see this
answer for an approach
to set strings to characters that are unavailable in the codepage
used by VBA.

Related

Matching MS Access accented characters - collation in MS Access

My immediate need is to do an accent-insensitive comparison in MS Access. I am using Office 365 Access.
This is not strictly speaking a Unicode question as the European accented characters are present in all of Windows-1252 (sometimes misleadingly called "ANSI" in Microsoft products and documentation), "modern" Unicode and UCS-2.
The Access "Data Types" page I found mentioned "two bytes per character", which makes it sound like UCS-2, but with no details. Similarly, the "sort order" drop-downs list a number of values that are also undocumented.
Actual example: compare "Dvorak" to "Dvořák". These are not equal in MS Access.
It is NOT my goal today to find a work-around (I can do that myself) - it is to better understand MS Access capabilities in 2023.
Having gone through the incremental support improvements for SQL Server and .NET strings, my first thought was "surely MS Access can handle collations by now (2023)".
My bottom line questions are: "exactly" what encodings ("sort orders") is Office 365 Access supporting in its most recent releases, and is VBA using the same character set, or will working with accented characters in VBA experience translations or issues when being used within MS Access?
You're not giving me a whole lot to go on, so I'll just go over the basics. It's important to note new features rarely make it to VBA and Access, and breaking changes are extremely rare, in contrast to new versions SQL server or C#.
Regarding charsets and encodings (how strings are stored):
Strings in tables, queries and application objects are stored in UTF-16. They may be compressed (unicode compression option for text fields). This is independent of sort orders.
The VBA code itself is stored in the local charset (which may not support certain characters). It's generally recommended to avoid non-ASCII characters in VBA code, as this may cause issues on different computers and different charsets. See this post for some trickery if you need non-ASCII characters in VBA literals.
VBA strings are always a BSTR which uses UTF-16 characters.
Regarding sort orders/collations (how strings are compared):
Access has no full support for collations, and no specific case sensitive/case insensitive and accent sensitive/accent insensitive collations.
It does support different sort orders, which determines how strings should be sorted and which characters are equal. An outdated list can be found here. Using the object browser in Access, you can navigate to LanguageConstants and check the list. In recent builds of Office 365, there are some new options that appear to use codepage 65001 (= UTF-8) but I haven't seen docs or experimented with it.
In VBA, string comparisons and sorts are determined by an Option Compare statement at the top of the module. Nearly all VBA applications only support two: Option Compare Binary, any inequality is an unequal string and sorts are case sensitive, and Option Compare Text, use the local language settings to compare strings. For Access, there's a third, Option Compare Database, use the database sort order to compare strings.
Note that not all functions support all unicode characters. Functions with limited support include MsgBox and Debug.Print. This can make it especially hard to debug code when working with characters not in the system code page.
Further notes
VBA does allow (relatively) easy access to the Windows API. Instead of rolling your own string comparison function, you could use CompareStringEx which has options to do case-insensitive diacritic-insensitive comparisons.
Note that for external functions, you need to pass string pointers using StrPtr, passing strings as a string will automatically convert them from a BSTR to a pointer to a null-terminated string in the system codepage. See this answer for a basic example how to call a WinAPI function for a unicode string. You will also have to look up and declare all the constants, e.g. Public Const NORM_IGNORECASE As Long = &H1, etc.

Funny characters in CSV files in Microsoft Works

For some reason, when I open a CSV file, that appears totally fine in Excel and Notepad, in Microsoft Works, there are some strange characters appearing as the first thing in the file. By first thing I mean they appear in cell A1, before the text that appears in that cell.
Here is an example file
Illustration carrier,Net death benefit,Issue date,Issue state,Policy type,Member lives,Policy date,Termination of coverage,Termination of coverage action required,Accumulated value,AV,SV,Illustrated Annual Level Premiums,LP to NDB ratio,Premium financed,Name of program,Primary insured age,Primary insured gender,Secondary insured age,Secondary insured gender,Current bid,Time left,Bid1,Bid2,Bid3,Bid4,Bid5,Bid6,Bid7,Bid8,Bid9,Bid10,Bid11,Bid12,Bid13,Bid14,Bid15,Bid16,Bid17,Bid18,Bid19,Bid20
srwer,$0.00,14/05/2012,us state 2,policy Type 1,member life 4,16/05/2012,-,,$0.00,-,-,,Not yet implemented,no,,0y 0m,Demale,,Female,$0.00,"2 days, 7 hours, 51 minutes, 36 seconds".
I create these files in my application using this method
protected ActionResult ExportToCSV(string csvExport)
{
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write(csvExport);
writer.Flush();
output.Position = 0;
return File(output, "text/comma-seperated-values", "export.csv");
}
I have a few questions
Is there a way to change this code to save the files in ANSI format?
Will I be able to view the files perfectly in Notepad, Works and Excel?
I suspect it's the UTF-8 byte order mark:

By convention, the presence of these characters at the beginning of a file indicate that the file is encoded using UTF-8. Modern applications look for these characters and automatically remove them if they exist. But Microsoft Works is an old application that probably doesn't support UTF-8.
To remove the characters, you can open the file in Notepad, choose File > Save As, and select ANSI in the Encoding drop-down list.
UPDATE: If you need to support old non-Unicode applications like Microsoft Works, then you can specify Encoding.ASCII or Encoding.Default when creating a text file in .NET. But MSDN Library cautions:
Different computers can use different encodings as the default, and the default encoding can even change on a single computer. Therefore, data streamed from one computer to another or even retrieved at different times on the same computer might be translated incorrectly. In addition, the encoding returned by the Default property uses best-fit fallback to map unsupported characters to characters supported by the code page. For these two reasons, using the default encoding is generally not recommended. To ensure that encoded bytes are decoded properly, your application should use a Unicode encoding, such as UTF8Encoding or UnicodeEncoding, with a preamble. Another option is to use a higher-level protocol to ensure that the same format is used for encoding and decoding.
Probably the csv is Unicode and these are Unicode "magic" characters indicating whether you have big or little endian? Just a guess.
Try the following:
StreamWriter writer= new StreamWriter(fullpath, false, Encoding.Unicode);

Problems with character sets

I have MS Access 2010 forms linking to a mySQL5 (utf8) database.
I have the following data stored in a varchar field:
"Jarosław Kot"
MS Access is just display this raw, as opposed to converting it to:
Jarosław Kot
Can anyone offer assistance?
Thanks Paul
The notation ł is a character reference in SGML, HTML, and XML. There is in general no reason to expect any software to treat it as anything but a literal of six characters “&”, “#”, etc., unless the software is interpreting the data as SGML, HTML, or XML.
So if you have data stored so that ł should be interpreted as a character reference, then you should convert the data, statically or dynamically. The specifics depend on what actual data there is—for example, do all the constructs use decimal notation (not hexadecimal), and is it certain that all numbers are to be interpreted as Unicode numbers for characters?
If I understand you correctly you can use Replace function:
Replace("Jarosław Kot", "ł", "ł")
Assuming that your mySQL database character set is effectively set to UTF8 and that all inserts and updates are utf8 compatible (I do not know that much about mySQL, but SQL Server has some specific syntax rules for utf8-compliant data...), you could then convert the available HTML data to plain UTF8 data.
You will not have any problem finding some conversion table (here for example), and, if you are lucky, you could even find a conversion function...

MySQL charset needed

I'm developing an application for a native language learning. I need to store some characters as 'ẽũ'. My database is set to utf-8 charset with a default collation, also the table affected by this characters.
The problem is when I try to add a row using a regular SQL insert:
INSERT INTO text(spanish,guarani) VALUES('text','ẽũ');
This throws a warning:
Warning Code : 1366 Incorrect string value: '\xE1\xBA\xBD\xC5\xA9' for column 'guarani' at row 1
And the result is "??" where there are those characters.
Question: These characters are not covered by the UTF-8 charset? Which one I need?
Note: Same problem with latin-1
Thanks.
QUICK!!! Read http://www.joelonsoftware.com/articles/Unicode.html
It is required reading.
Once you have read that, you should ask yourself:
What encoding is the connection using.
What locale is collation using. (If applicable).
What encoding is the SQL statement in?
What encoding are the string literals in?
What encoding is the html form presented in?
As by other answer, you really should read and understand the basics of Unicode.
It's not difficult, (in one day you can grasp it), it's required knowledge for almost every programmer (and certainly for you), it's non ephemeral knowledge and will be your life simpler and happier.
These characters are not covered by
the UTF-8 charset?
UTF-8 is a Unicode charset, Unicode covers (practically) every character. MYSQL's 'utf8' encoding, on the other hand, is not true UTF-8, it leaves some characters out (thouse outside the BMP). But that is not your problem here.
http://www.fileformat.info/info/unicode/char/1ebd/index.htm
http://www.fileformat.info/info/unicode/char/169/index.htm
You see there that your two characters are valid Unicode, are inside the BMP (hence Mysql crippled 'utf8' should support them), and yu can even see it's UTF-8 encoding. And, as you see, \xE1\xBA\xBD\xC5\xA9 seems just right. So the problem seems to be elsewhere. Are you sure you DB is utf8?

How do I find the character encoding of a ms access database?

How do I find out the character encoding for the tables in my MS Access 2003 database.
For example:
Windows-1252
ISO 8859-1
US-ASCII
Is there something not working with CurrentDB.CollatingOrder? I don't know where you look up the value of the resulting number, but in my American DBs, it returns 1033, which is quite familiar as the American English character set.
Ah, yes, if I go into the Object Browser in the VBE and search for CollatingOrder, one of the results shows an ENUM called CollatingOrderEnum, and by clicking on each in turn, you can see its value.
DBEngine(0)(0).CollatingOrder is the same property, and can be used with DAO from outside Access. There is, perhaps, a way to get it with ADO/OLEDB, but I don't use either of them so can't point you in the right direction there.
Beginning with Access_2000 (which was based on Jet 4.0), Access databases store text data internally as Unicode. So if your database file really is an Access_2003 database then the DAO, ODBC, and OLEDB access methods should all return Unicode strings.