2016-01-06 93 views
0

我最近寫了這個簡短的函數,但在VBA中很少有經驗,我不明白爲什麼這不起作用。VBA(Excel)問題與校驗數公式

Sub barcodedigit() 
Dim barcode(12) As Variant 
Dim i As Integer 
Dim oddscount As Integer 
Dim evenscount As Integer 
Dim evensnumbers As Integer 
Dim oddsnumbers As Integer 
Dim finalnumber As Double 
Dim remainder As Integer 
oddsnumbers = 0 
evensnumbers = 0 

For i = 1 To 12 

barcode(i) = InputBox("Please enter number" & i) 

Next i 

For i = 1 To 12 
If barcode(i) Mod 2 = 0 Then 
evenscount = evenscount + 1 And evensnumbers = evensnumbers + barcode(i) 

Else 

oddscount = oddscount + 1 And oddsnumbers = oddsnumbers + barcode(i) 


End If 

Next i 

oddsnumbers = oddsnumbers * 3 

finalnumber = oddsnumbers + evensnumbers 

remainder = finalnumber Mod 10 

MsgBox ("Oddscount is equal to " & oddscount & vbNewLine & "Remainder is equal to" & " " & remainder) 
End Sub 

我在這裏的問題是,這是設置每個結果爲0(oddscount &餘數),即使這按理應該工作。

任何幫助表示讚賞。

編輯::刪除和完美工作!

+2

不要以爲你需要和,只需使用2行代碼。 –

回答

2

你按位And很奇怪—我想你的意思

If barcode(i) Mod 2 = 0 Then 
    evenscount = evenscount + 1 
    evensnumbers = evensnumbers + barcode(i) 
Else 
    oddscount = oddscount + 1 
    oddsnumbers = oddsnumbers + barcode(i) 
End If 
0

我寫了類似的東西here。這裏是代碼:

Function IsCodeValid(sNumber As String) As Boolean 
    On Error Resume Next 
    If Len(sNumber) < 8 Then Exit Function 
    IsCodeValid = (Right(sNumber, 1) = CheckDigit(Left(sNumber, Len(sNumber) - 1))) 
    If Err.Number <> 0 Then Debug.Print Now, sNumber, Err.Number, Err.Description 
End Function 

Function CheckDigit(ByVal gtin As String) As String 
'general purpose check digit calculator 
'given all figures except last one, calculate check digit as used for GTIN-8, GTIN-12, EAN13, EDI GLN, etc... 
'parameter: number as string, WITHOUT the last digit 
'   works with string length up to 254 char 
'returns: the last digit 
'author: Patrick Honorez - www.idevlop.com 
'notes:  provided without any warranties 
'   Copyleft as long as you keep this header intact 
'help for algorithm can be found here: 
'   http://www.gs1.org/barcodes/support/check_digit_calculator#how 

    Dim m() As String, lSum As Long, i As Integer 
    Dim chk As Integer, large As Long, mult As Byte 
    'store string into an array 
    m = Split(StrConv(gtin, vbUnicode), Chr(0)) 
    mult = 3 'multiplier initial value is 3 
    'calc right to left to start with 3 as multiplier 
    For i = UBound(m) - 1 To 0 Step -1 'ignore last value of array: it's always = to chr(0) 
     lSum = lSum + Val(m(i)) * mult 
     If mult = 3 Then mult = 1 Else mult = 3 'swap multiplier value between 3 and 1 
    Next i 
    'find difference between lSum and the 10 that's equal or greater 
    large = (lSum \ 10) * 10 
    If large < lSum Then large = large + 10 
    chk = large - lSum 
    CheckDigit = CStr(chk) 
End Function