2017-05-31 25 views
2

我的問題聽起來很愚蠢,但我嘗試了幾種在互聯網上暴露無疑的解決方案。我完全不熟悉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 

預先感謝您的幫助!

編輯:這是我在文件中獲取的行的示例: Log Level:LogLevel |文件名:X:\ Folder1 \ Folder2 \ Folder3 \ Folder4 \ Folder5 \ Folder6 \ FileName.h |函數名稱:FunctionName |行號:XXXX |信息:MYINFO | BLABLA | VALUE1 = 32768 | VALUE2 = 0.000000 | VALUE3 = 1.580000 | VALUE4 = 0.000000 | VALUE5 = 3581.941895 | VALUE6 = 36349.941406

我目前正試圖獲得VALUE3。

+2

強烈考慮使用**雙**與**單**。 –

+0

即使這些值只在-32768和32768之間? – ZulKaz

+0

Y9u需要使用一個斷點並檢查你認爲是一個數字的字符串的值。變量valueToRead中可能有字母字符。直接在導致錯誤的行之前嘗試「debug.print valueToRead」。 –

回答

0

只是猜測你不在美國/英國。在德國,您有,而不是.作爲區域設置。因此,添加此字符串,鑄造前:

Public Function change_commas(ByVal myValue As Variant) As String 

    Dim str_temp As String 

    str_temp = CStr(myValue) 
    change_commas = Replace(str_temp, ",", ".") 

End Function 
+1

OP的問題是相反的方向... –

+0

@TimWilliams - 你是對的。 – Vityata

+0

我現在得到了什麼問題!謝謝大家的快速回答:) 是否也有可能知道爲什麼Double比Single更好? – ZulKaz