通过Excel VBA计算小数位数

时间:2014-07-02 13:30:24

标签: excel vba

在我的Excel中,有不同类型的十进制数,小数位也不同。

EG。 112.33, 112.356, 145.1, 25.01, 27.001

我需要知道具有2位小数位的单元格数,例如 - 25.01 - 应该是其中之一。 我需要这个代码用于excel VBA

4 个答案:

答案 0 :(得分:3)

您可以使用VBA技术,如以下示例所示:

Dim digit As Integer
Dim num As Double
num = 123.456
digit = Len(CStr(num)) - InStr(CStr(num), ".")

其中digit是小数位数。

与您的第一个样本相关:

digit = Len(CStr(112.33)) - InStr(CStr(112.33), ".")

RGDS,

答案 1 :(得分:0)

对于十进制字符(句号或逗号)未知的情况,可以扩展Alex的答案。如果从Excel工作表中获取数字并且事先未知区域设置,则可能是这样。另一个扩展是处理缺少小数的(整数)数字。

Dim iDigits As Integer
Dim vNumber As Variant

vNumber = Excel.Application.ActiveCell.value

If VBA.IsNumeric(vNumber) And Not VBA.IsEmpty(vNumber) Then
    iDigits = Len(vNumber) - Len(VBA.Fix(vNumber))

    ' correct for decimal character if iDigits > 0
    iDigits = IIf(iDigits > 0, iDigits - 1, 0)
Else
    iDigits = 0
End If

答案 2 :(得分:0)

   import { NgModule } from '@angular/core';
   import { BrowserModule } from '@angular/platform-browser';
   import { FormsModule, ReactiveFormsModule } from '@angular/forms';
   import { HttpModule } from '@angular/http';
   import { RouterModule, Routes } from '@angular/router';

   import { AppComponent }  from './app.component';

   import { HomeComponent } from './home/home.component';

   import { LoginComponent } from './login/login.component';
   import { AlertService } from './login/services/alert.service';
   import { AlertComponent } from './directives/alert.component';
   import { AuthenticationService } from './login/services/authentication.service';
   import { AuthGuard } from './guards/auth.guard';

@NgModule({
imports: [ 
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    RouterModule.forRoot([

        { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
        { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
        { path: 'login', component: LoginComponent },
        { path: '**', redirectTo: '', pathMatch: 'full' }

      ]) 
],
providers: [
    AuthGuard,
    AlertService,
    AuthenticationService
],
declarations: [ 
    LoginComponent,
    AlertComponent,
    HomeComponent,
    AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }

答案 3 :(得分:0)

改进MatthewHagemann提交的非常方便的功能。

此版本;

  • 当用户将多个单元格作为该函数的范围传递给用户时,不会出错

  • 不管单元格中的数字是存储为文本还是存储为数字

VBA:

Function CountDecimalPlaces(InputCell As Range) As Integer
'Counts the number of decimal places in a cell
Dim StringConvert As String

If InputCell.Cells.Count > 1 Then
    CountDecimalPlaces = 0
    Exit Function
End If

StringConvert = InputCell.Value

If InStr(1, StringConvert, ".") = 0 Then
    CountDecimalPlaces = 0
Else
    CountDecimalPlaces = Len(StringConvert) - InStr(1, StringConvert, ".")
End If

End Function