Excel에서 VBA를 사용하여 이중으로 잘라내기
텍스트 상자에 표시하기 위해 두 배 값의 소수점 자리 수를 잘라내야 합니다.vba로 이를 어떻게 달성할 수 있습니까?
값을 반올림하려면 반올림 함수를 사용할 수 있습니다(단, VBA의 반올림 함수는 뱅커 반올림(Banker's Round)이라고도 하며 위 또는 아래로 5번 반올림합니다. 기존 반올림을 사용하면 형식을 사용합니다).
반올림하지 않고 값을 자를 경우, 허용된 답과 같이 문자열을 사용할 필요가 없습니다. 단지 수학을 사용합니다.
Dim lDecimalPlaces As Long: lDecimalPlaces = 2
Dim dblValue As Double: dblValue = 2.345
Dim lScale = 10 ^ lDecimalPlaces
Dim dblTruncated As Double: dblTruncated = Fix(dblValue * lScale) / lScale
이 값은 "2.34"입니다.
사용하실 수 있습니다.ROUND위해서FORMATVBA에서
예를 들어 소수점 2자리를 표시하는 경우
Dval = 1.56789
Debug.Print Round(dVal,2)
Debug.Print Format(dVal,"0.00")
참고: 위의 내용은 다음과 같습니다.1.57. 그래서 만약 당신이 찾고 있다면,1.56그러면 Dval을 문자열에 저장하고 이렇게 할 수 있습니다.
Dim strVal As String
dVal = 1.56789
strVal = dVal
If InStr(1, strVal, ".") Then
Debug.Print Split(strVal, ".")(0) & "." & Left(Split(strVal, ".")(1), 2)
Else
Debug.Print dVal
End If
Int() 기능을 사용할 수 있습니다.Debug.print Int(1.99543)
또는 Better:
Public Function Trunc(ByVal value As Double, ByVal num As Integer) As Double
Trunc = Int(value * (10 ^ num)) / (10 ^ num)
End Function
사용하시면 됩니다.Trunc(1.99543, 4)==>result: 1.9954
이것은 내가 시도한 것입니다.
Function TruncateNumber(decimalNum As Double, decPlaces As Integer) As Double
'decimalNum: the input number to be truncated
'decPlaces: how many decimal places to round to. Use 0 for no decimal places.
decimalLocation = InStr(decimalNum, ".")
TruncateNumber = Left(decimalNum, decimalLocation + decPlaces)
End Function
다른 반올림 방법으로 인해 발생하는 수학 오류를 방지하기 위해 문자열을 사용합니다.그것은 두 배의 형식으로 출력되므로 당신은 여전히 그것에 대해 자신만의 수학을 수행할 수 있습니다.
소수점 자리가 없는 숫자를 위 함수에 전달하면 오류가 발생합니다.이 문제가 발생할 경우 다음 코드를 대신 사용할 수 있습니다.
Function TruncateNumber(decimalNum As Double, decPlaces As Integer) As Double
'decimalNum: the input number to be truncated
'decPlaces: how many decimal places to round to. Use 0 for no decimal places.
If InStr(decimalNum, ".") = 0 Then 'if there was no decimal:
'then return the number that was given
TruncateNumber = decimalNum
Else 'if there is a decimal:
'then return the truncated value as a type double
decimalLocation = InStr(decimalNum, ".")
TruncateNumber = Left(decimalNum, decimalLocation + decPlaces)
End If
End Function
이러한 기능들이 누군가에게 유용하기를 바랍니다.광범위한 테스트를 해보지는 못했지만, 그들은 제게 효과가 있었습니다.
편집됨
최신 버전의 Excel(VBA)에는 이미 제대로 작동하는 TRUNK 기능이 있습니다.
EXCEL의 이전 버전의 경우
나는 두 배를 정수로 자르고 싶었습니다.
value = Int(83.768)
value == 83
대박, 잘 됐어요.
Excel(VB) 버전에 따라 음수에서는 작동하지 않을 수 있습니다.
value = Int(-83.768)
value == -84
VB는 뱅커 라운딩을 사용합니다.
Public Function Trunc1(ByVal value As Double) As Integer
' Truncate by calling Int on the Absolute value then multiply by the sign of the value.
' Int cannot truncate doubles that are negative
Trunc1 = Sgn(value) * Int(Abs(value))
End Function
특정 소수점 자리를 원하는 경우 마카가 값 주변에서 Abs로만 수행한 작업을 수행하여 Int가 제대로 자를 수 있도록 합니다.
Public Function Trunc2(ByVal value As Double, Optional ByVal num As Integer = 1) As Double
' Truncate by calling Int on the Absolute value then multiply by the sign of the value.
' Int cannot truncate doubles that are negative
Trunc2 = Sgn(value) * (Int(Abs(value) * (10 ^ num)) / (10 ^ num))
End Function
여기 제가 한 작은 실험이 있습니다.(처음 글을 올리고 답변을 드리는데, 혹시 제가 규정을 지키지 않는다면 말씀해 주시기 바랍니다.
Sub Truncate()
Dim dblNum As Double
Dim intDecimal As Integer
dblNum = 1578.56789
intDecimal = 2 '0 returns 1578
'2 returns 1578.56
'-2 returns 1500
Debug.Print (Int(dblNum * 10 ^ intDecimal) / 10 ^ intDecimal)
End Sub
언급URL : https://stackoverflow.com/questions/11347704/truncating-double-with-vba-in-excel
'programing' 카테고리의 다른 글
| MariaDB 구문 오류를 확인하는 방법(Error Code 1064)? (0) | 2023.09.07 |
|---|---|
| 파워셸의 비트와이즈 연산자 사용 (0) | 2023.09.07 |
| 에 Powershell v2.0을 내장하고 있습니다.Windows 8 RTM의 NET 앱 (0) | 2023.09.07 |
| 프로그램적으로 뷰를 뷰에 추가하는 방법 (0) | 2023.09.07 |
| 예기치 않은 AUTO_INCRECTION 동작 (0) | 2023.09.07 |