简体   繁体   中英

Excel VBA - Macro that creates new worksheets causes weird malfunction

I've created a macro that is supposed to add (say 100) new worksheets to my excel workbook. These new worksheets are supposed to be named like this: 1% , 1.1% , 1.2% , 1.3% ,..., 9.9% , 10% .

Sub AddWorkSheets()
Dim i As Double
For i = 0 To 10 Step 0.1
   Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = i & "%"
Next i
End Sub

When I run this code everything works fine at first - it adds new worksheets named as stated above. But it only works until worksheet 5.9% . After that worksheet all others get names like 5.99999999 , 6.09999999 , 7.2999999 and so on. Does anyone have an explanation why that happens?

This occurs becouse you are using a for-next loop with floating point math, where fractional numbers can't be exactly represented.

Tons of explanations here on SO, of why this occurs. Below, a way to correct your code.

Sub AddWorkSheets()
Dim i As Double
For i = 0 To 100 Step 1
  Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = round(i/10,1) & "%"
Next i
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM