Vba cint ошибка

Аннотация

В системе программирования Microsoft Visual Basic при использовании функции CInt () с строкой, которая не может быть преобразована в число, появляется следующее сообщение об ошибке:

Ошибка во время выполнения «13»: несоответствие типов

Дополнительная информация

Функция CInt преобразует выражение в целое число. Можно использовать любое допустимое числовое или строковое выражение, но строковое выражение должно быть преобразовано в число. В справочных материалах Visual Basic указано, что следует использовать функцию CInt вместо функции Val для предоставления одновременных преобразований из любого другого типа данных в целое число. Однако эти две функции не работают точно. При использовании функции Val для возврата чисел, содержащихся в строке, возвращаются только первые цифры в строке. Несмотря на то, что функция Val возвращает только числовую часть строкового выражения, функция CInt возвращает сообщение об ошибке, приведенное выше, если строковое выражение не может обрабатываться как число. Ниже приведена таблица выражений и значений, возвращаемых функциями CInt и Val. Expression Value Returned ——————————————— Val(«1726 56th Ave NE») 172656 CInt(«1726 56th Ave NE») Error message Val(«asdf») 0 Cint(«asdf») Error message Val(«1,000») 1 CInt(«1,000») 1000 Val(«1.34») 1.34 CInt(«1.34») 1 Поскольку функция Val возвращает значение 0 при использовании с выражением, которое содержит 0 или вообще не имеет чисел, его нельзя использовать для проверки, является ли входная строка допустимым числом. Однако вы можете использовать функцию CInt в процедуре, чтобы определить, является ли строка ввода допустимым числом.

Ссылки

Для получения дополнительных сведений о функции CInt нажмите кнопку «Поиск» в справочнике по Visual Basic и введите:

CVErr

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.

Summary

In Microsoft Visual Basic Programming System, Applications Edition, when you use the CInt() function with a string that cannot be converted to a number, you receive the following error message:

Run-time error ’13’:

Type Mismatch

More Information

The CInt function converts an expression to an integer. You can use any valid numeric or string expression, but the string expression must be able to be converted to a number. The Visual Basic Reference states that you should use the CInt function instead of the Val function to provide internationally aware conversions from any other data type to Integer. However, the two functions do not behave exactly the same.

When you use the Val function to return the numbers contained in a string, only the first numeric characters in the string are returned. While the Val function returns only the numeric part of a string expression, the CInt function returns the error message above if the string expression cannot be evaluated as a number.

The following is a table of expressions and values returned by the CInt and the Val functions.

Expression Value Returned
———————————————
Val(«1726 56th Ave NE») 172656
CInt(«1726 56th Ave NE») Error message
Val(«asdf») 0
Cint(«asdf») Error message
Val(«1,000») 1
CInt(«1,000») 1000
Val(«1.34») 1.34
CInt(«1.34») 1

Because the Val function returns the value 0 when used with an expression that contains either 0 or no numbers at all, you cannot use it to test whether an input string is a valid number. You can, however, use the CInt function in a procedure to determine whether an input string is a valid number.

References

For more information about the CInt Function, choose the Search button in the Visual Basic Reference and type:

CInt

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

I am trying to make a function that looks at an image, and return the X pixel value.

When i run the code, it throws an error on the Int1=CInt(Xdim) line, saying «Type Mismatch (10080)»

If i hard-code the value i am testing into Xdim, it works fine.

Function ImgXDim(filename As String) As Integer         ' Finds the X dimension in pixels of a loaded image
Dim objShell As Object
Dim objFolder As Object
Dim objFile As Object
Dim ImgSize As String
Dim Int1 As Integer
Dim Xdim As String
Dim strarray() As String

Set objShell = CreateObject("Shell.Application")

Set objFolder = objShell.NameSpace(MacroDir & "PICS")
Set objFile = objFolder.ParseName(filename)

ImgSize = objFile.ExtendedProperty("Dimensions")        ' Returns string of "700 x 923"

strarray = Split(ImgSize, " x ")                        ' Split into 2 strings of "700" and "923"
Xdim = CStr(strarray(0))                                ' Force Xdim to be a string of "700"
Int1 = CInt(Xdim)                                       ' Convert Xdim to an integer
ImgXDim = Int1                                          ' Return Integer

End Function

DisplayName's user avatar

DisplayName

13.2k2 gold badges11 silver badges19 bronze badges

asked Mar 14, 2018 at 21:59

J Smith's user avatar

1

First check if value can be converted to an integer:

 If IsNumeric(Trim(Xdim)) then 
   Int1 = CInt(Xdim)
 else
   'for debug purposes
   MsgBox ("XDim non-numeric or empty")
 End If 

answered Mar 14, 2018 at 23:49

6

Ok, i couldnt find what character was causing the issue, so i used this loop of code to pull out only numbers, and it seems to work.

For X = 1 To Len(Xdim)
    If IsNumeric(Mid(Xdim, X, 1)) = True Then
       holder = holder & Mid(Xdim, X, 1)
    End If
Next X

answered Mar 15, 2018 at 19:19

J Smith's user avatar

J SmithJ Smith

392 silver badges5 bronze badges

1

Here the WIA version:

Function ImgXDim(filename As String) As Long        
     Dim imgWIA as New WIA.ImageFile 'Early Binding needs a reference to Windows Image Aquisition Library in VBA-Ide->Tools->References
    'Dim imgWIA as Object 'Late Bound Version
    'Set imgWIA = CreateObject("WIA.ImageFile")
    imgWIA.LoadFile MacroDir & "PICS" & filename
    ImgXDim = imgWIA.Width ' use .Height for height
End Function

As you see, just three lines of code and returns a long, not a string that needs parsing.

Useful functions for resize, rotate and more.

Also useful if you want to display Tiffs in a picture control (page by page) and more.

answered Mar 15, 2018 at 19:59

ComputerVersteher's user avatar

Return to VBA Code Examples

In this Article

  • CInt Function
    • VBA CInt Convert Expression to Integer
    • VBA CInt Rounding
    • VBA CInt Converting Strings to Integers
    • VBA CInt Run-Time Error 13 Type Mismatch
    • VBA CInt Run-Time Error 6 Overflow
    • VBA CInt Regional Settings
    • VBA CInt Converting Booleans to Integers
    • VBA CInt Converting Dates to Integers

This tutorial will demonstrate how to use the CInt VBA function to convert an expression to the integer data type.

CInt Function

VBA CInt Convert Expression to Integer

The VBA CInt function can be used to convert expressions to integer data type inside VBA code. The resulting number is rounded to become an integer.

Sub CIntExample_1()
MsgBox CInt(12.34)  'Result is: 12
MsgBox CInt(12.345) 'Result is: 12
MsgBox CInt(-124)   'Result is: -124
MsgBox CInt(-12.34) 'Result is: -12
End Sub

VBA CInt Rounding

The VBA CInt function will round the decimal part of a number type or a number like expression. However, it does not round correctly in all cases. When the decimal part is 0.5 then VBA CInt function returns the closest even integer.

Sub CIntExample_2()
MsgBox CInt(0.34)
'Result is:    0

MsgBox CInt(0.99)
'Result is:    1

MsgBox CInt(-124.95)
'Result is:    -125

MsgBox CInt(1.5)
'Result is:    2

MsgBox CInt(2.5)
'Result is:    2
End Sub

We can add a decimal number relatively small to our expected decimal value to change the behavior of VBA Cint function to the expected.

Sub CIntExample_3()
MsgBox CInt(2.5)
'Result is:    2
MsgBox CInt(2.5 + 0.001)
'Result is:    3

MsgBox CInt(14.5)
'Result is:   14
MsgBox CInt(14.5 + 0.001)
'Result is:   15
End Sub

VBA CInt Converting Strings to Integers

The VBA CInt function can be used to convert strings to integers if the characters in the string have a meaning as numbers.

Sub CIntExample_4()
Dim StrEx As String
StrEx = "112"
MsgBox CInt(StrEx)
'Result is: 112

StrEx = "112.3"
MsgBox CInt(StrEx)
'Result is: 112   --> 112.3 is rounded

StrEx = "11,2"
MsgBox CInt(StrEx)
'Result is: 112   -->  , is ignored

StrEx = "$112"
MsgBox CInt(StrEx)
'Result is: 112   -->  $ is ignored
End Sub

VBA CInt Run-Time Error 13 Type Mismatch

Using VBA Cint function with strings that contain non-numerical characters or characters that don’t have meaning in numerical context will result in a Run-Time error ’13’: Type mismatch.

Sub CIntExample_5()
'The code below will result in an ERROR message
'CInt can’t handle non numerical characters
Dim StrEx As String
StrEx = "Ab13"
MsgBox CInt(StrEx)
End Sub

VBA CInt Run-Time Error 6 Overflow

Using VBA Cint function with strings that result in a value smaller or bigger than the expected integer will result in a Run-Time error ’6’: Overflow. Integer data type in excel has an expected value of -32768 to 32767.

Sub CIntExample_6()
'The code below will result in an ERROR message
'CInt cant handle non numerical characters
Dim StrEx As String
StrEx = "1234567"
MsgBox CInt(StrEx)
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

VBA CInt Regional Settings

VBA CInt function has different behavior converting strings with comma or dot.  It uses the Regional Settings of the operating system for decimal separator and digit separator.

Sub CIntExample_7()
Dim StrEx As String
StrEx = "1,9"
MsgBox CInt(StrEx)
‘If Regional settings have , as a grouping separator then 
'Result is: 19
‘If Regional settings have , as a decimal separator then 
'Result is: 2 (2 because 1.9 gets rounded)

StrEx = "1.9"
MsgBox CInt(StrEx)
‘If Regional settings have . as a grouping separator then 
'Result is: 19
‘If Regional settings have . as a decimal separator then 
'Result is: 2 (2 because 1.9 gets rounded)
End Sub

VBA CInt Converting Booleans to Integers

VBA Cint function can convert boolean variables to integers. If the evaluated expression is true the resulting integer is -1 and if the evaluated expression is false, the resulting integer is 0.

Sub CIntExample_8()
Dim BoolEx As Boolean
BoolEx = True
MsgBox CInt(BoolEx)  'Result is: -1
MsgBox CInt(2 = 2)   'Result is: -1

BoolEx = False
MsgBox CInt(BoolEx)  'Result is: 0
MsgBox CInt(1 = 2)   'Result is: 0
End Sub

VBA CInt Converting Dates to Integers

VBA Cint function can convert a date variable to an integer. The returned value is the internal number used by excel for date storage rounded. If that number is outside of the expected integer limits for VBA then we get a  Run-Time error ’6’: Overflow.

Sub CIntExample_9()
Dim DateEx As Date
DateEx = #2/3/1940#
MsgBox CInt(DateEx)
'Result is: 14644
DateEx = #8/7/1964#
MsgBox CInt(DateEx)
'Result is: 23596
End Sub

I am experiencing difficulty with the following VBS code. It works only sometimes, and even then it fails quickly. Why?

Dim Butt
Set Butt = CreateObject("InternetExplorer.application")
Butt.visible = True
Butt2 = InputBox("Put the link to one hat you would like to snipe.", "Hat Selection")
Butt3 = InputBox("Enter the maximum amount of Robux you will spend on this hat.", "Maximum Payment")
Dim Proace
Set Proace = CreateObject("Microsoft.XMLHTTP")
Proace.Open "GET", "http://www.roblox.com", False
Proace.Send
Do
Do While Butt.Busy
WScript.sleep 200
Loop
St00f = CInt(Replace(Mid(St00f, (InStr(St00f, ">R$")+3), 8), "</b>", ""))
If St00f <= CInt(Butt3) Then
Butt.Navigate "javascript:WebForm_DoPostBackWithOptions(new%20WebForm_PostBackOptions(""ctl00$cphRoblox$TabbedInfo$UserSalesTab$lstItemsForResale$ctrl0$lnkBuyNow"",%20"""",%20true,%20"""",%20"""",%20false,%20true))"
Exit Do
End If
Loop
Do While Butt.Busy
WScript.sleep 200
Loop
MsgBox("Congratulations! Your snipe was successful! You sniped "&Butt2&" for "&Butt3&" Robux!")
Butt.Quit
Set Butt = Nothing
Set Proace = Nothing
WScript.Quit

Error:

Script:   C:UsersJohnDownloadsSingleHatSniper.vbs  
Line:     14
Char:     1
Error:    Type mismatch: 'CInt'
Code:     800A000D
Source:   Microsoft VBScript runtime error

Please help me, I’m not that great with VBS. That much is clear, my friend helped me write this.

Понравилась статья? Поделить с друзьями:
  • Vba byref ошибка
  • Vba autofill ошибка
  • Vba autocad обработка ошибок
  • Vba access ошибка 3265
  • Vba access обработка ошибок