![](/img/trans.png)
[英]C# Loop round a Range.Value which has 2 objects [0,0] to find if string = variable
[英]Range.Value produces different results in VBA and C#
我注意到Range.Value在VBA和C#中為日期值產生不同的結果。
例如,如果單元格的值為5/13/1988且NumberFormat為d / m / yyyy,則在VBA Range.Value中將返回“5/13/1988”,而在C#中則返回“5/13/1988 12:00:00”上午”
Range.Value2在兩種語言中都是相同的(32276)。
有誰知道為什么VBA和C#在這種情況下會產生不一致的結果?
請注意,我知道我可以使用Range.Value2和Range.NumberFormat的組合,然后在C#中格式化值,但我感興趣的是為什么行為不一致。
簡單。 在Excel Interop(您在VSTO項目中引用)中,MS顯然已將Date單元格值映射到.Net DateTime數據類型。
對他們來說是最好的選擇,你不希望像Date .Net數據類型一樣使用(記住VB classic只有Date數據類型而不是DateTime)。
請參閱excel如何處理數據: https : //stackoverflow.com/a/13983731
VB.Net和C#處理它的方式不同。
Excel 2013
Sub Sample()
MsgBox Sheet1.Range("A1").Value
End Sub
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
C#2013
C#很遺憾像你提到的那樣處理它。
您可以這樣做以獲得所需的結果
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
//
}
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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.