PDA

View Full Version : HEX file (".bmp") into EXCEL



andysuth
06-30-2009, 05:12 AM
I'm trying to perform a mathematical function on a hex file.

I need to read in a 100 x 1 pixel bitmap file into excel and perform a mathematical function on the coulours contained within.

I've done this manually with a HexEditor program but need to repeat the process many times.

I've read .CSV and .TAB files into Excel, and altered text in a text file before using Excel Macros, but I've never read Hexadecimal values into Excel before.

(I'll also need to save HEX values back into the BitMap once I've processed them).

Has anyone done anything like this before?

I've not actually tried altering code yet, but I was going to see if the routines for reading a text file could be modified to read a HEX file.

Is there a resource that could point me in the right direction?

-Andy.

Oorang
06-30-2009, 07:45 AM
This is just rough throw away code, but it should give the basics:
Option Explicit

Public Sub HexReader()
Dim bytFileInfo() As Byte
Dim strFilePath As String
Dim lngRow As Long
Dim lngCol As Long
Dim lngUprBnd As Long
Dim lngIndx As Long
strFilePath = Excel.Application.GetOpenFilename
If strFilePath = "False" Then Exit Sub
bytFileInfo = GetFileBytes(strFilePath)
lngUprBnd = UBound(bytFileInfo)
Sheet1.UsedRange.Delete
Sheet1.Range("A:I").NumberFormat = "@"
For lngRow = 0 To lngUprBnd
For lngCol = 1 To 8
Sheet1.Cells(lngRow + 1, lngCol).Value = Right$("00" & _
Hex$(bytFileInfo(lngIndx)), 2)
lngIndx = lngIndx + 1
If lngIndx > lngUprBnd Then GoTo BreakOut
Next
Next
BreakOut:
AddReadOut
With Sheet1.UsedRange
.HorizontalAlignment = xlHAlignLeft
.Columns.AutoFit
.Font.Name = "Consolas"
End With
End Sub

Private Sub AddReadOut()
Dim lngRow As Long
Dim lngCol As Long
Dim strVal As String
For lngRow = 1 To Sheet1.UsedRange.Rows.Count
For lngCol = 1 To 8
If LenB(Sheet1.Cells(lngRow, lngCol).Value) Then
strVal = strVal & ChrW$(CLng("&H" & Sheet1.Cells(lngRow, _
lngCol).Value))
Else
Exit For
End If
Next
Sheet1.Cells(lngRow, 9).Value = Excel.WorksheetFunction.Clean(strVal)
strVal = vbNullString
Next
End Sub

Private Function GetFileBytes(ByVal path As String) As Byte()
Dim lngFileNum As Long
Dim bytRtnVal() As Byte
lngFileNum = FreeFile
Open path For Binary Access Read Lock Write As #lngFileNum
ReDim bytRtnVal(LOF(lngFileNum)) As Byte
Get lngFileNum, , bytRtnVal
Close lngFileNum
GetFileBytes = bytRtnVal
End Function