如何在excel中将度/分转换为十进制?

时间:2013-05-15 07:31:14

标签: excel excel-vba vba

我已经google了很多,但没有找到任何解决方案。我想在Latcel中将Lat Long数据(度,分,秒)转换为十进制。

传统上lat长数据就像25°43'21.3",但我工作的数据库没有度(°)符号,它有点(。)而不是度。例如 - 25.43'21.3" < / p>

那么将25.43'21.3"转换为十进制的脚本是什么样的 - 25.722583333333333 ??

当数据附带(°)符号时,以下代码有效。

    Function Convert_Decimal(Degree_Deg As String) As Double
   ' Declare the variables to be double precision floating-point.
   Dim degrees As Double
   Dim minutes As Double
   Dim seconds As Double
   ' Set degree to value before "°" of Argument Passed.
   degrees = Val(Left(Degree_Deg, InStr(1, Degree_Deg, "°") - 1))
   ' Set minutes to the value between the "°" and the "'"
   ' of the text string for the variable Degree_Deg divided by
   ' 60. The Val function converts the text string to a number.
   minutes = Val(Mid(Degree_Deg, InStr(1, Degree_Deg, "°") + 2, _
             InStr(1, Degree_Deg, "'") - InStr(1, Degree_Deg, _
             "°") - 2)) / 60
    ' Set seconds to the number to the right of "'" that is
    ' converted to a value and then divided by 3600.
    seconds = Val(Mid(Degree_Deg, InStr(1, Degree_Deg, "'") + _
            2, Len(Degree_Deg) - InStr(1, Degree_Deg, "'") - 2)) _
            / 3600
   Convert_Decimal = degrees + minutes + seconds
End Function

1 个答案:

答案 0 :(得分:2)

这样做:

Private Const vbQuote As String = """"

Public Sub test()
    Debug.Print answer("25.43'21.3""")
End Sub


Public Function answer(ByVal s As String) As Double
    Dim degrees As Double
    Dim minutes As Double
    Dim seconds As Double

    Dim dotPos As Integer 'position of first dot in the string
    Dim commaPos As Integer 'position of comma in the string
    Dim quotePos As Integer 'position of quote in the string

    dotPos = InStr(s, ".")
    commaPos = InStr(s, "'")
    quotePos = InStr(s, vbQuote)

    If dotPos = 0 Or _
        commaPos = 0 Or _
        quotePos = 0 Or _
        dotPos > commaPos Or _
        commaPos > quotePos Then

        'some error handling here
        Stop
    End If

    degrees = CDbl(Left(s, dotPos - 1))
    minutes = CDbl(Mid(s, dotPos + 1, commaPos - dotPos - 1))
    seconds = CDbl(Mid(s, commaPos + 1, quotePos - commaPos - 1))

    answer = degrees + minutes / 60 + seconds / 3600

End Function