PDA

View Full Version : [SOLVED:] VBA Formatting Help



AK_Beaver
02-02-2017, 07:02 PM
Hi, I'm new to this site and figured it might be a good place to get some help. I'm trying to format my DD to DMS VBA code so that the out put is 00-00-00. If the number is less then 10, I need the number to lead with a 0, such as 01, 02, etc. I have tried every formatting concept I know, which isn't a lot because I'm new to VBA. I'd appreciate any help you can give. Thank You!

Here's my code with test function (It runs great in its current form, its just the wrong format):
---------------------------------------------------------------------------------------------------
Function DD2DASH(dDDAngle As Double) As String

'Converts DD angles to DMS angles in dash format

Dim dDegrees As Double
Dim dMinutes As Double
Dim dSeconds As Double

'Find Degrees

dDegrees = Int(dDDAngle)

'Find Minutes

dMinutes = (dDDAngle - dDegrees) * 60

'Find Seconds

dSeconds = Format(((dMinutes - Int(dMinutes)) * 60), "00.00000000")

'Convert to DMS in dash form and return value

DD2DASH = dDegrees & "-" & Int(dMinutes) & "-" & dSeconds

End Function
--------------------------------------------------------------------------------------------
Sub Test_DD2Dash()

Dim MyDD2DASH As String

MyDD2DASH = DD2DASH(8.705)

Debug.Print MyDD2DASH

End Sub

Kenneth Hobs
02-02-2017, 08:58 PM
Welcome to the forum! Please paste code between code tags. Click # on toolbar to insert the tags.

Add some more format()'s?

Sub Test_DD2Dash()
Dim MyDD2DASH$
MyDD2DASH = DD2DASH(8.705)
Debug.Print 8.705, MyDD2DASH
End Sub


'Converts DD angles to DMS angles in dash format
Function DD2DASH(dDDAngle As Double) As String
Dim dDegrees As Double, dMinutes As Double, dSeconds#

'Find Degrees
dDegrees = Int(dDDAngle)

'Find Minutes
dMinutes = (dDDAngle - dDegrees) * 60

'Find Seconds
dSeconds = Format(((dMinutes - Int(dMinutes)) * 60), "00.00000000")

'Convert to DMS in dash form and return value
DD2DASH = Format(dDegrees, "00") & "-" & Format(Int(dMinutes), "00") & "-" & dSeconds
End Function

AK_Beaver
02-03-2017, 01:58 AM
Thank You so much! That solved my problem. I tried everything but what you did. Thanks again!

p45cal
02-03-2017, 10:30 AM
You can also do the following, if your decimal degrees are in cell A1, then in another cell:
=A1/24
and custom format that cell:
[hh]-mm-ss
which will give you a single leading zero if the decimal dgrees value is less than 10.
If you want you can use
[hhh]-mm-ss
since degrees often go above 100, giving you more leading zeroes.

Extending this to a function:
Function DD2DASHb(dDDAngle) As String
DD2DASHb = Application.Text(dDDAngle / 24, "[hh]-mm-ss") 'you could use [hhh] instead.
End Function
used in a worksheet thus:
=DD2DASHb(A1)
(or from other code).

Afterthought: if you wanted decimal seconds in the result, then throughout (worksheet number format or in the function) you can use the likes of:
[hh]-mm-ss.00