Excel VBA单元格值显示为整数

我正在使用Excel的VBAfunction编写程序,但遇到了一个非常奇怪的逻辑错误。

For SheetIndex = 1 To 6 With ActiveSheet For ColIndex = 2 To 6 For DateIndex = 0 To MinLimit datethingy = .Cells(1, ColIndex).Value If (.Cells(1, ColIndex).Value = Date_Array(DateIndex, 1)) Then For RowIndex = 2 To 11 ' Compare every time slot value here to every time slot value in the array datethingy = Trim(CStr(.Cells(RowIndex, 1).Value)) 'ERROR OCCURS HERE If (Trim(CStr(.Cells(RowIndex, 1).Value)) = Date_Array(DateIndex, 2)) Then .Cells(RowIndex, ColIndex).Value = "Checked" End If Next End If Next Next End With SheetIndex = SheetIndex + 1 Application.Worksheets(SheetIndex).Activate Next 

所以在上面的代码中,我会经历一系列的单元格值,并对我在数组中已有的值进行比较。 但是,当我从单元格中绘制值时,而不是“8:30”,它会显示为“0.354166666 … 7”。 我不知道为什么它会这样,我甚至确保它被比较为一个string,而不是一个int或其他任何东西。

这里是我设置表格单元格的值。

 .Cells(2, 1).Value = "8:30" .Cells(3, 1).Value = "9:00" .Cells(4, 1).Value = "10:15" .Cells(5, 1).Value = "11:30" .Cells(6, 1).Value = "12:30" .Cells(7, 1).Value = "13:30" .Cells(8, 1).Value = "14:45" .Cells(9, 1).Value = "16:00" .Cells(10, 1).Value = "17:15" .Cells(11, 1).Value = "18:15" With Range("A2", "A11") .HorizontalAlignment = xlCenter .Font.Bold = True .ColumnWidth = 15 End With ActiveSheet.Cells.Rows.AutoFit 

有谁知道为什么会发生这种情况?

Excel将时间和date存储为数字。 每个整数都是一天,小时,分钟和秒钟被分解成当天的小数部分。 8:30只是一个没有整数的时间,8.5 / 24 = 0.3541667。

你可以用这个代码来testing这个,这可能为你提供一种格式化input的方法。 在单元格A1中键入8:30

 Sub test() Debug.Print sheet1.Range("A1").Value = "8:30" 'returns false Debug.Print Format(sheet1.Range("A1").Value, "h:mm") = "8:30" 'returns true Debug.Print Sheet1.Range("A1").Text = "8:30" 'return true End Sub