How to create a file from hex code in Excel/VBA - excel

I have code in hexadecimal format in an excel workbook. Each 2-digit piece of code is in a separate cell, so it looks like 4D|54|68|64|00|00|00|06 etc. There may also be a few cells with 4 or 6 digit pieces, if it makes it any simpler. Is there any way to code a file from here? Effectively I need it so that opening the file in a hex editor will reveal the code. I have a feeling this may involve HEX2DEC or HEX2BIN, but even then I wouldn't know where to go from there.

Might not be the most efficient solution in terms of converting the strings to bytes, but just opening a file in binary mode and putting bytes to it works just fine:
Sub HexStringToBinaryFile()
Dim hex_val As String
hex_val = "4D|54|68|64|00|00|00|06"
Dim output() As String
output = Split(hex_val, "|")
Dim handle As Long
handle = FreeFile
Open "C:\Dev\test.bin" For Binary As #handle
Dim i As Long
For i = LBound(output) To UBound(output)
Put #handle, , CByte("&H" & output(i))
Next i
Close #handle
End Sub

You didn't actually say what you did but textfile functions do character conversions. Use a stream object in binary mode to write to disk. Use write method to put a byte array into it. And like textfile functions avoid VBA's character or string functions.
Sub test()
Dim ByteArray(4) As Byte
ByteArray(0) = CByte(55)
ByteArray(1) = CByte(55)
ByteArray(2) = CByte(55)
ByteArray(3) = CByte(55)
Set BS = CreateObject("ADODB.Stream")
BS.Type = 1
BS.Open
BS.Write ByteArray
BS.SaveToFile "c:\users\test", 2
End Sub

Related

Fastest way to transfer array to text file

I have a one dimensional array with more than 3 million items and I would like to transfer it to a text file. I tried a FileSystemObject method, which is not fast enough for me. So I tried to write to cells in a worksheet and export it as txt file, but I am still searching for a faster way to write an array to a txt file.
Please try also Put (and maybe later also Get):
Private Sub TestPut(myArray() as string)
Dim handle As Long
handle = FreeFile
Open Application.Defaultfilepath & "\Whatever.txt" For Binary As #handle
Put #handle, , myArray
Close #handle
End Sub
You may join your array as a single string to prevent unwanted descriptors (see above Put-documentation) and to define CR or CRLF or whatever as delimiter,
but only if the resulting string's length does not exceed 2,147,483,647 bytes:
Put #handle, , Join(myArray, vbCrLf)
Try something like that
FilePath = "C:\output.txt"
Set FileStream = CreateObject("ADODB.Stream")
FileStream.Open
FileStream.Type = 2 'Text
FileStream.Charset = "utf-8"
FileStream.WriteText vba.Strings.Join(YourArray)
FileStream.SaveToFile (FilePath)
FileStream.Close

How to change encoding from UTF-8 to UTF-8-BOM of exported *.txt files from Excel?

Exported text files from Excel are encoded with UTF-8.
An encoding UTF-8-BOM is needed.
I think that in code shall be inserted a row, written like:
Java
?xml version="1.0" encoding="UTF-8"?
Jasperreport CSV UTF-8 without BOM instead of UTF-8
or
HTML5
meta charset="utf-8"
Bad UTF-8 without BOM encoding
Sub export_data()
Dim row, column, i, j As Integer
Dim fullPath, myFile As String
fullPath = "C:\Workspace"
row = 21
column = 5
For i = 1 To column
myFile = Cells(1, i).Value + ".txt"
myFile = fullPath + "/" + myFile
Open myFile For Output As #1
For j = 2 To row
Print #1, Cells(j, i).Value
Next j
Close #1
Next i
End Sub
How can I define and where to put a row, which defines encoding UTF-8-BOM?
Thank You.
Instead of Printing the file line by line, it might be more efficient to
save your selected range as a CSV UTF-8
you might need to change the file type after saving
Use ADO to process the file as UTF-8
Either will add a BOM automatically.
EDIT
If you are unfamiliar, you could perform the save to csv - utf8 process manually with the macro recorder turned on. Then examine what you have recorded and make appropriate edits.
Another way of adding the BOM, in the context of your existing code, would be to write it directly as a byte array to the first line.
For example:
Dim BOM(0 To 2) As Byte 'EF BB BF
BOM(0) = &HEF
BOM(1) = &HBB
BOM(2) = &HBF
Open myFile For Binary Access Write As #1
Put #1, 1, BOM
Close #1
will put the BOM at the beginning of the file.
You should then change the mode in your subsequent Print code to Append.
I suggest you read about the pros and cons of using Print vs Write
You should also read about declaration statements. In yours, only the last variable on each line is being declared as the specified type; the preceding variables are being implicitly declared as being of type Variant.

Finding a certain type of String in Visual Basic and replacing it

I'm currently trying to automate our accounting process. From the bank, I download a .csv file that I'd like to transform in a certain way. I'm also attempting to eliminate all IBAN and BIC numbers from the document as they're not necessary for the accounting process.
Now, every IBAN and BIC follows a certain pattern. How do I replace all strings with a certain pattern (i.e. XX00000000000000 and DEXXXXXXXXX) or at least how do I find them using Visual Basic? I'm familiar with the .replace method already, I just cannot manage to find the string.
Thank you so much in advance!
I think this should help you:
RegEx
An another way could be to load each textline of the .csv file into an array and just Loop through them.
Something like:
Dim Textline() As String 'array
Dim IBAN As String
Dim posIBAN As Integer
Dim iban_length As Integer
textlinelength = UBound(Textline)
iban_length = 22
For i = 0 To textlinelength
If InStr(Textline(i), "DE") Then 'if array contains DE
posIBAN = InStr(Textline(i), "DE") 'find position of IBAN
IBAN = Mid(Textline(i), posIBAN, iban_length) 'get IBAN
Textline(i) = Replace(Textline(i), IBAN, "") 'replace IBAN with ""
End If
Next i
After that you could create a new file and write the arrays in it.
So you would have a IBAN-free txt-file
PS: Is there a way to properly link other questions/answers?

save csv as pipe delimited using vba

I have a csv file which has data as shown below:
PPIC,11/20/2013 10:23,11431,10963,,Tremors ,
PPIC,11/20/2013 10:23,11431,11592,,"Glioblastoma, Barin ",
the key difference is that row 1 contains a single word (last column), whereas the second row contains data enclosed in double quotes (but comma separated)
This is causing my BULK Import routine to import data wrong for second row. when BULK IMPORT runs, it splits the second row into multiple columns.
I read lots of posts on StackOverflow, and lots of suggestions point out to have a "pipe" delimited file as the input for bulk insert, that will remove any inconsistencies with the quoted text.
How can I convert this comma separated file into a pipe delimited file using a vb excel macro? I want to keep the process automated (where it will take the input csv file, convert it to pipe delimited and then send the file further for importing).
OR
How can I address the inconsistent quotes to be used whilst doing a BULK Insert?
Any thoughts / help appreciated.
This would do it:
Sub MySub()
Dim FileString As String
Dim Pattern As String
Dim ReplacementPattern As String
Dim ChangedStr As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
FileString = "PPIC,11/20/2013 10:23,11431,10963,,Tremors ," & vbCrLf & "PPIC,11/20/2013 10:23,11431,11592,,""Glioblastoma, Barin "","
Pattern = "(""[^""]*""|[^"",]*)?,"
ReplacementPattern = "$1|"
RE.Pattern = Pattern
RE.Global = True
RE.MultiLine = True
ChangedStr = RE.Replace(mystr, ReplacementPattern)
End Sub
Hope this does the trick

declaring a unicode string in vba in excel [duplicate]

This question already has answers here:
How to type Unicode currency character in Visual Basic Editor
(2 answers)
Closed 3 years ago.
I am trying to create a substitute() that will convert greek characters to latin.
The problem is that after declaring
Dim Source As String
Source = "αβγδεζηικλμνξοπρστθφω"
Source is interpreted as "áâãäåæçéêëìíîïðñóôõöù"
is there any way use unicode at declaration level?
You can try StrConv:
StrConv("αβγδεζηικλμνξοπρστθφω", vbUnicode)
Source : http://www.techonthenet.com/excel/formulas/strconv.php
[EDIT] Another solution:
You can get every greek character (lower and upper case) thanks to this procedure:
Sub x()
Dim i As Long
For i = 913 To 969
With Cells(i - 912, 1)
.Formula = "=dec2hex(" & i & ")"
.Offset(, 1).Value = ChrW$(i)
End With
Next i
End Sub
You can create an array to find the char for instance.
Source: http://www.excelforum.com/excel-programming/636544-adding-greek-letters.html
[EDIT 2] Here is a sub to build the string you wanted:
Sub greekAlpha()
Dim sAlpha As String
Dim lLetter As Long
For lLetter = &H3B1 To &H3C9
sAlpha = sAlpha & ChrW(lLetter)
Next
End Sub
As previously mentioned, VBA does support unicode strings, however you cannot write unicode strings inside your code, because the VBA editor only allows VBA files to be encoded in the 8-bit codepage Windows-1252.
You can however convert a binary equivalent of the unicode string you wish to have:
str = StrConv("±²³´µ¶·¹º»¼½¾¿ÀÁÃĸÆÉ", vbFromUnicode)
'str value is now "αβγδεζηικλμνξοπρστθφω"
Use notepad to convert the string: copy-paste the unicode string, save the file as unicode (not utf-8) and open it as ASCII (which is in fact Windows-1252), then copy-paste it into the VBA editor without the first two characters (ÿþ), which is the BOM marker
You say that your source is interpreted as "áâãäåæçéêëìíîïðñóôõöù".
Note that the Visual Basic Editor doesn't display Unicode, but it does support manipulating Unicode strings:
Dim strValue As String
strValue = Range("A1").Value
Range("B1").Value = Mid(strValue, 3)
Range("C1").Value = StrReverse(strValue)
If A1 contains Greek characters, B1 and C1 will contain Greek characters too after running this code.
You just can't view the values properly in the Immediate window, or in a MsgBox.

Resources