【发布时间】:2017-05-31 13:53:48
【问题描述】:
我的问题可能听起来很愚蠢,但我尝试了几种在互联网上公开的解决方案,但均未成功。我是 VBA 的新手。
问题: 我正在从 txt 文件中提取数据。该数据存储在字符串中,我需要将该值存储到单个变量中。
背景: 我使用的是 Microsoft Excel 2010,代码是在 Microsoft Visual Basic for Applications 下完成的。
我尝试过的解决方案: 在所有这些情况下,valueToRead 都等于“1.580000”。
1) realAngle = CSng(valueToRead) 我收到执行错误“13”,类型不兼容
2) realAngle = Single.Parse(valueToRead) 编译错误,语法错误
3) realAngle = Single.Parse(valueToRead, System.Globalization.NumberFormatInfo.InvariantInfo) 编译错误,语法错误
4) realAngle = Convert.ToSingle(valueToRead) 执行错误“424”:需要对象
我的代码如下:
Sub macro_test()
' File to read data from
Dim logFile As String
' Variable containing a line from the file
Dim textLine As String
' Variable containing a part of the line
Dim ReadValue As Variant
' Variable containing a part of ReadValue
Dim ReadValue2 As Variant
' Desperate variable in order to be sure to have a String value
Dim valueToRead As String
' Angle value stored in the file
Dim realAngle As Single
' Number of elements separated by " | " in the lien
Dim Size As Integer
' Initialize variables
Size = 0
realAngle = 0
logFile = "FilePathAndName"
' Open the txt file
Open logFile For Input As #1
' Read until the end of the file
Do Until EOF(1)
' Get a line of text from the file
Line Input #1, textLine
' Split the line with " | " separator
ReadValue = Split(textLine, " | ")
' Count the number of elements
Size = UBound(ReadValue) - LBound(ReadValue) + 1
' If the line have enough elements then it may be of interest
If Size > 9 Then
' if this is the correct line thanks to a correct identificator
If ReadValue(3) = "MyIdentificator" Then
' Split the line with the " = " sign
ReadValue2 = Split(ReadValue(8), " = ")
' Storing the value into a String
valueToRead = ReadValue2(1)
realAngle = CSng(valueToRead)
'realAngle = Single.Parse(valueToRead)
'realAngle = Convert.ToSingle(valueToRead)
'realAngle = Single.Parse(valueToRead, System.Globalization.NumberFormatInfo.InvariantInfo)
End If
End If
Loop
Close #1
End Sub
提前感谢您的帮助!
编辑:这是我在文件中获得的行的示例: 日志级别:LogLevel |文件名:X:\Folder1\Folder2\Folder3\Folder4\Folder5\Folder6\FileName.h |函数名:函数名|行号:XXXX |信息:MYINFO |布拉布拉|值 1 = 32768 |值 2 = 0.000000 | VALUE3 = 1.580000 |值 4 = 0.000000 | VALUE5 = 3581.941895 | VALUE6 = 36349.941406
我目前正在尝试获取 VALUE3。
【问题讨论】:
-
强烈考虑使用 Double 与 Single。
-
即使值仅在 -32768 和 32768 之间?
-
Y9u 需要使用断点并检查您认为是数字的字符串的值。变量 valueToRead 中可能有字母字符。在导致错误的行之前直接尝试“debug.print valueToRead”。
-
我尝试将 realAngle 更改为 double 并使用 realAngle = CDbl(valueToRead) 但我仍然出现“执行错误 '13',类型不兼容”。我正在使用断点,字符串的值为“1.580000”,然后当我尝试将值设置为 realAngle 时出现问题。
-
您的区域设置是什么?是你的小数 a 。或 , ?