Range.Value在VBA和C#中产生不同的结果

时间:2015-09-05 02:48:56

标签: c# vba excel-vba vsto excel

我注意到Range.Value在VBA和C#中为日期值产生不同的结果。

例如,如果单元格的值为5/13/1988且NumberFormat为d / m / yyyy,则在VBA Range.Value中将返回“5/13/1988”,而在C#中则返回“5/13/1988 12: 00:00 AM“

Range.Value2在两种语言中都是相同的(32276)。

有没有人知道为什么VBA和C#会在这种情况下产生不一致的结果?

请注意,我知道我可以使用Range.Value2和Range.NumberFormat的组合,然后在C#中格式化值,但我感兴趣的是为什么行为不一致。

3 个答案:

答案 0 :(得分:1)

简单。在Excel Interop(您在VSTO项目中引用)中,MS显然已将Date单元格值映射到.Net DateTime数据类型。

对他们来说是最好的选择,你不会想像Date .Net数据类型一样使用(记住VB classic只有Date数据类型而不是DateTime)。

在此处查看Excel如何处理数据:https://stackoverflow.com/a/13983731

答案 1 :(得分:1)

VB.Net和C#处理它的方式不同。

Excel 2013

enter image description here

Sub Sample()
    MsgBox Sheet1.Range("A1").Value
End Sub

enter image description here

VB.Net 2013

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    '~~> Opens an existing Workbook. Change path and filename as applicable
    xlWorkBook = xlApp.Workbooks.Open("C:\Users\Siddharth\Desktop\Delete Later\Sample.xlsx")

    '~~> Display Excel
    xlApp.Visible = True
    xlWorkSheet = xlWorkBook.Sheets("Sheet1")

    MessageBox.Show(xlWorkSheet.Range("A1").Value)

    '
    '~~> Rest of the code
    '
End Sub

enter image description here

C#2013

C#很遗憾就像你提到的那样处理它。

enter image description here

您可以这样做以获得所需的结果

    private void button1_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();

        xlexcel.Visible=true ;

        xlWorkBook = xlexcel.Workbooks.Open(
                    "C:\\Users\\Siddharth\\Desktop\\Delete Later\\Sample.xlsx", 
                    0, true, 5, "", "", true, 
                    Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, 
                    "\t", false, false, 0, true, 1, 0);

        // Set Sheet 1 as the sheet you want to work with
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        String cellvalue = xlWorkSheet.Cells[1, 1].Value.ToString("MM/dd/yyyy", 
                           CultureInfo.InvariantCulture);

        MessageBox.Show(cellvalue);

        //
        //~~> Rest of the code
        //
    }

enter image description here

答案 2 :(得分:-1)

using System.Threading;
using System.Globalization;
// Put the following code before InitializeComponent()
// Sets the culture to US English
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 
// Sets the UI culture too
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");