在Excel中转​​换时间格式

时间:2016-03-29 18:22:32

标签: excel excel-formula excel-2010

如何将以字符串形式输出的时间值(21m49s)转换为Excel时间值(00:21:49)?如果没有给出小时值,则不为该单元分配0h值。在这种情况下,它只会显示分钟和秒钟。

还需要考虑60分钟以上的读数,显示为1h34m14s。

这是我收到时间值的方式:

image

这就是我需要它们的样子:

image

2 个答案:

答案 0 :(得分:1)

试试这个:

using (OleDbConnection conn = new OleDbConnection())
{
    conn.ConnectionString = connection.dbdataSource;
    conn.Open();

    foreach (var listBoxItem in ServicePartsList.Items)
    {
        item = listBoxItem.ToString();
        string[] result = item.Split(',');
        MessageBox.Show(result[0] + result[1]);
        // insert into database
        using (OleDbCommand addPart = new OleDbCommand())
        {
            //Open Connection

            addPart.Connection = conn;

            addPart.CommandText = "INSERT INTO servicePart (ServiceID, PartNo, Quantity) VALUES (@sID, " + "@partNo, " + "@quantity)";
            addPart.Parameters.AddWithValue("sID", ModelCode + ModelYear + ButtonClick);
            addPart.Parameters.AddWithValue("partNo", result[0]);
            addPart.Parameters.AddWithValue("quantity", result[1]);

            //execute SQL
            int recordsAdded = addPart.ExecuteNonQuery();

        }
    }
    //Close DB Connection
    conn.Close();
}

enter image description here

虽然@Jeeped打败了我,但我会发布我的UDF:

=TIME(IF(ISNUMBER(FIND("h",A1)),LEFT(A1,FIND("h",A1)-1),0),IF(ISNUMBER(FIND("m",A1)),IF(ISNUMBER(FIND("h",A1)),MID(A1,FIND("h",A1)+1,FIND("m",A1)-1-FIND("h",A1)),LEFT(A1,FIND("m",A1)-1)),0),IF(ISNUMBER(FIND("s",A1)),IF(ISNUMBER(FIND("m",A1)),MID(A1,FIND("m",A1)+1,LEN(A1)-1-FIND("m",A1)),LEFT(A1,FIND("s",A1)-1)),0))

enter image description here

答案 1 :(得分:1)

可能是VBAUDF¹。

Function realTime(str As String) As Double
    Dim t As Long, vTMs As Variant, vTMP As Variant

    vTMs = Array("h", 0, "m", 0, "s", 0)
    vTMP = Array(str & ChrW(8203))

    For t = LBound(vTMs) To UBound(vTMs) Step 2
        vTMP = Split(vTMP(0), vTMs(t))
        If IsNumeric(vTMP(0)) Then
            vTMs(t + 1) = Int(vTMP(0))
            vTMP(0) = vTMP(1)
        End If
    Next t

    realTime = TimeSerial(vTMs(1), vTMs(3), vTMs(5))

End Function

realTme_UDF

¹用户定义函数(又名UDF)被放入标准模块代码表中。点击 Alt + F11 ,当VBE打开时,立即使用下拉菜单插入►模块 Alt + 中号)。将功能代码粘贴到标题为 Book1 - Module1(Code)的新模块代码表中。点击 Alt + Q 返回工作表。