[Visual Basic] 纯文本查看 复制代码 Sub CalculateCRC()
Dim dataRange As Range
Dim dataCell As Range
Dim dataArray() As Byte
Dim crc As Integer
Dim highByte As String
Dim lowByte As String
Set dataRange = Range("O38:AZ38")
ReDim dataArray(0 To dataRange.Cells.Count - 1)
For Each dataCell In dataRange
dataArray(dataCell.Column - dataRange.Column) = Val("&H" & dataCell.Value)
Next dataCell
crc = CRC16_Modbus(dataArray, UBound(dataArray) + 1)
highByte = "0x" & Right("00" & Hex((crc \ &H100) And &HFF), 2)
lowByte = "0x" & Right("00" & Hex(crc And &HFF), 2)
MsgBox "CRC16-Modbus校验值为:" & highByte & " " & lowByte
With ThisWorkbook.Worksheets("Sheet1")
.Range("BA37").Value = highByte
.Range("BB37").Value = lowByte
End With
End Sub
Function CRC16_Modbus(data() As Byte, ByVal length As Integer) As Integer
Dim crc As Integer
Dim i As Integer
Dim j As Integer
crc = &HFFFF
For i = 0 To length - 1 Step 1
crc = crc Xor data(i)
For j = 1 To 8
If crc And &H1 Then
crc = (crc \ 2) Xor &HA001
Else
crc = crc \ 2
End If
Next j
Next i
CRC16_Modbus = crc
End Function
|