+ Reply to Thread
Results 1 to 14 of 14

VBA calculate checksum xor of string

Hybrid View

  1. #1
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    VBA calculate checksum xor of string

    Hello everybody,

    Let me first wish you all the best and every success for 2021. Here is my problem.

    Given an alphanumeric string, whatever length of said string, say 1 up to X<20 characters, whatever number of strings in a selected excel spreadsheet column, I need to :

    1. calculate the checksum xor of each string, based on ascii value of each character of the string,
    2. convert xor calculated checksum value into hexadecimal, making sure that the hex checksum is a 2-digit string : if the hex conversion returns only one digit hex checksum, add a zero ("0") before the cheksum value),
    3. concatenate said hex 2-digit checksum with the corresponding string in some adjacent column.

    I have used scadacore checksum online calculator to obtain the correct ascii based xor values.

    Anyway I am grateful for any feedback, again thank you in advance for your advices.

    BR
    Attached Files Attached Files

  2. #2
    Forum Guru karedog's Avatar
    Join Date
    10-03-2014
    Location
    Indonesia
    MS-Off Ver
    2003
    Posts
    2,971

    Re: VBA calculate checksum xor of string

    Maybe :
    Sub Test()
      Dim cell As Range, chk As Long, i As Long, str1 As String
      For Each cell In Range("A2:A4")
          str1 = cell.Value
          chk = Asc(Left$(str1, 1))
          For i = 2 To Len(str1)
              chk = chk Xor Asc(Mid$(str1, i, 1))
          Next i
          cell.Offset(, 3).Value = cell.Value & Right$("00" & Hex(chk), 2)
      Next cell
    End Sub
    1. I care dog
    2. I am a loop maniac
    3. Forum rules link : Click here
    3.33. Don't forget to mark the thread as solved, this is important

  3. #3
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    Hi Karedog,
    Thank you for your post.
    I will try right away and let you know.

  4. #4
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    Thank you Karedog
    Works like a charm !
    I will now try to understand the exact meaning of Mid$, and why you start with chk = Asc(Left$(str1, 1)) (the need to specify starting "left" maybe ?)
    I just need to dimension the Range("A2:A4") to suit the proper size .
    Again, merci beaucoup !

  5. #5
    Forum Guru karedog's Avatar
    Join Date
    10-03-2014
    Location
    Indonesia
    MS-Off Ver
    2003
    Posts
    2,971

    Re: VBA calculate checksum xor of string

    You are welcome.

    We are xor-ing each character in a string, the result is put on variable chk.
    For first character, we simply put it directly on variable chk.
    For the rest characters (starting from second chars), we use mid$() to get character at examined position and xor-ing with currect chk value.

    Regards

  6. #6
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    Thank you Karedog,
    The code works and I have added some other values in column A.
    But as you can see in the attachments, when I call the 'Test' macro, an error message pops up and then , the debug points at "chk = Asc(Left$(str1, 1)) ".
    Again, it works and the data flow is processed, the xored chains are correct. But I do not understand where does this "error '5' incorrect procedure" come from ?
    Attached Images Attached Images

  7. #7
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    This function works, but I need to copy it for each string, which is not what I need.
    I would like the thousands of chains in column A to be xored "at once" by calling a function or algorithm .
    However I have noticed that there is no mention of specific treatment whatsoever for the first digit of the string, before switching to next.

    Function Chainxor(ByVal X As String) As String
    Dim S As Byte, P As Integer
    For P = 1 To Len(X)
    S = S Xor Asc(Mid$(X, P, 1))
    Next P
    Chainxor = X & Right$("0" & Hex$(S), 2)
    End Function

    BR

  8. #8
    Forum Guru karedog's Avatar
    Join Date
    10-03-2014
    Location
    Indonesia
    MS-Off Ver
    2003
    Posts
    2,971

    Re: VBA calculate checksum xor of string

    Hi decolit,

    You are welcome.
    And since you are a new member here, please read the forum rules first here :
    https://www.excelforum.com/forum-rul...rum-rules.html

    Here in excelforum, the VBA code must be enclosed in code tags (rule no 2), so please edit your post on #7 using this code tags.


    To answer your questions :

    Quote Originally Posted by decolit View Post
    ... But I do not understand where does this "error '5' incorrect procedure" come from ?
    You have blank cell(s) on the range, for example if using the workbook you posted on #1, and then empty cell A2, this error will be popped up, since the code looping in the range A2:A4, and A3 is empty.
    If you have some blank cells, additional code must be put in to overcome this error (to skip the blank cells).

    Quote Originally Posted by decolit View Post
    ...However I have noticed that there is no mention of specific treatment whatsoever for the first digit of the string, before switching to next.
    Because the udf you make only process one input string (not many input cells, using loop), the 's' variable is not needed to be reset for the next use, that's the reason.

    For example, if the VBA code on post #2 is like this :
    Sub TestWrong()
      Dim cell As Range, chk As Long, i As Long, str1 As String
      For Each cell In Range("A2:A4")
          str1 = cell.Value
          '''REM chk = Asc(Left$(str1, 1))
          For i = 1 To Len(str1)
              chk = chk Xor Asc(Mid$(str1, i, 1))
          Next i
          cell.Offset(, 3).Value = cell.Value & Right$("00" & Hex(chk), 2)
      Next cell
    End Sub
    For the first input (cell A2 --> D2) the result is correct, but for the rest of cells will produce incorrect results, since the variable is not reset (carry previous value).

  9. #9
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    Hello Karedog,
    Thank you for your reply.
    I apologise for not having respected the rules of the forum, and I will be more careful next time I insert code in my post.
    I've got your explanation.
    To avoid this error, I have thought of using kind of a filter like this :
    For Each cell In Range("A2:A")
        If Not IsEmpty(cell) Then
            'do sth
        End If
    Next
    Would this solve the pop up error '5' ?
    Thank you again

  10. #10
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    Finally, I came up with this structure, for looping only non empty cells :

    Sub TestWrong()
      Dim cell As Range, chk As Long, i As Long, str1 As String
        For Each cell In Range("A2:A1000")
        If Not IsEmpty(cell) Then
          str1 = cell.Value
        chk = Asc(Left$(str1, 1))
          For i = 2 To Len(str1)
              chk = chk Xor Asc(Mid$(str1, i, 1))
          Next i
          cell.Offset(, 2).Value = cell.Value & Right$("00" & Hex$(chk), 2)
          End If
      Next cell
    End Sub
    Now I understand better why we need :
     chk = Asc(Left$(str1, 1))
          For i = 2 To Len(str1)
    I have checked the hex xoring result with this function and it works fine :
    Function Chkxor(ByVal X As String) As String
       Dim S As Byte, P As Integer
       For P = 1 To Len(X)
          S = S Xor Asc(Mid$(X, P, 1))
          Next P
       Chkxor = Right$("0" & Hex$(S), 2)
       End Function
    Because I do not want to limit the numbers of strings to a given value (can be unknown and not preset Z strings), I have tried to express the working range by using :

    For Each cell In Range("A2:A")
        If Not IsEmpty(cell) Then
            'do sth
        End If
    Next
    But the code won't work, it returns an error saying range not defined, or smtg like that. Any idea ?

    Here is the file for you to check. Again, thank you very much Karedog for your patient explanations.
    Attached Files Attached Files

  11. #11
    Forum Guru
    Join Date
    02-27-2016
    Location
    Vietnam
    MS-Off Ver
    2024
    Posts
    6,179

    Re: VBA calculate checksum xor of string

    Try this:

    PHP Code: 
    Sub TestWrong3()
      
    Dim Arr As Variant,  As Long,  lastRow As Long
      lastRow 
    Range("A" Rows.Count).End(xlUp).Row
      Arr 
    Range("A2:A" lastRow).Value
        
    For 1 To UBound(Arr)
            If 
    Arr(i1) <> "" Then Arr(i1) = Arr(i1) & Chkxor(Arr(i1))
        
    Next i
      Range
    ("C2").Resize(UBound(Arr), 1) = Arr
    End Sub 
    Last edited by Phuocam; 01-03-2021 at 08:41 AM.

  12. #12
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Re: VBA calculate checksum xor of string

    Hello Phuocam,
    Best wishes for 2021!
    Now, this is perfect. Because I am unable to write the proper codes or specify the nature of variant, and arrays, can you please explain the tools that you have used to make "A2:A" range work ?
    Thank you for your help.

  13. #13
    Forum Guru karedog's Avatar
    Join Date
    10-03-2014
    Location
    Indonesia
    MS-Off Ver
    2003
    Posts
    2,971

    Re: VBA calculate checksum xor of string

    decolit,

    I see that Phuocam has helped you to solve the whole program, and you only need explanation about the "A2:A" range part.

    For explaining with illustration, please open your workbook posted on #10.

    We want to get last cell on column A, in this case, it is cell A101.

    Here are the steps if we do it manually :
    - Move the cursor to the last cell on column A, in this case, it is cell A1048576
    - Now, on your keyboard, press "End" key, then "Up" key
    - The cursor now jumps to cell A101, the one we are looking for

    Now we can mimic this using VBA macro, paste and run this code :
    Sub Explanation()
      Debug.Print Rows.Count                                '--> 1048576
      Debug.Print Range("A" & Rows.Count).Address           '--> $A$1048576
    
      lastRow = Range("A" & Rows.Count).End(xlUp).Row
      Debug.Print lastRow                                   '--> 101
    
      Debug.Print Range("A2:A" & lastRow).Address           '--> $A$2:$A$101
    End Sub
    Phuocam's code start from cell $A$1048576 --> Range("A" & Rows.Count) , then jumps up using the ".End(xlUp)" method, the followed by ".Row" property, to get the last row on Column A
    And then we just join the obtained lastrow from previous step --> Range("A2:A" & lastRow) --> now we get the expected range $A$2:$A$101
    These steps become standard procedure when we want to get the last cell of a column, just memorize this, you will use this technique a lot.

  14. #14
    Registered User
    Join Date
    02-03-2020
    Location
    france
    MS-Off Ver
    7
    Posts
    11

    Red face Re: VBA calculate checksum xor of string

    Hi Karedog,
    With your detailed explanation, it makes sense now for me.
    It's very clear : the code which seems opaque is in fact the simple "translation" of what we would manually with the keyboard or with the cell/range address selection in excel spreadsheet.
    if you allow me, I will copy your explanations and store them for further use.
    Again thank you and Phuocam for everything.
    BR

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Calculate CCITT 16-bit checksum from string
    By hubertmettwurst in forum Excel Programming / VBA / Macros
    Replies: 9
    Last Post: 11-07-2022, 12:48 AM
  2. [SOLVED] Calculate CRC32 checksum :)
    By mc84excel in forum Excel Programming / VBA / Macros
    Replies: 11
    Last Post: 06-13-2016, 11:22 AM
  3. [SOLVED] One Digit Checksum
    By mc84excel in forum Excel Programming / VBA / Macros
    Replies: 12
    Last Post: 10-27-2014, 09:45 PM
  4. Generate MD5 Checksum
    By vibs_us in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 02-06-2008, 02:25 PM
  5. Table Checksum
    By astrikor in forum Excel Formulas & Functions
    Replies: 6
    Last Post: 01-16-2008, 10:11 AM
  6. [SOLVED] Calculate Checksum
    By Safi in forum Excel Formulas & Functions
    Replies: 1
    Last Post: 07-23-2006, 09:40 AM
  7. [SOLVED] Calculate Checksum
    By Safi in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 07-23-2006, 03:40 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1