我有一个包含大量代码的电子表格,这完全取决于我使用它的机器,如果一个=TEXT()函数中的日期格式不像预期的那样工作的话。
我家里有两台电脑,都有相同版本的Excel- -一台台式机和一台笔记本电脑,都有英文版的Excel。它适用于台式机,但不适用于笔记本电脑,显然是不同的区域设置。再一次,它工作在德国的机器与德国的地区设置-在那里,它应该工作。
我所假设的是,使用yyyymmdd将产生20221125的今天,无论是一台机器。事实证明,事实并非如此,从图片中可以看到。超级令人恼火。
为了减轻这种情况,我现在检查
=TEXT(A1,"yyyymmdd")
=TEXT(A1,"jjjjMMTT")例如,在A1是已知日期的情况下,该字段的结果应该是20000101。另一种同样有效的方法是在文本公式的结果中查找"yyyymmdd“中的字母。
一旦找到正确的字符串,我就可以进一步使用它来格式化所有日期。
这是可行的,但超级令人恼火。

有没有一种方法可以不跳过圈就知道区域设置?
发布于 2022-11-26 01:26:51
不要使用日期字符串,而是使用定义的名称:
eg: =Text(N11, dtFormat)在工作簿模块中输入此自动打开事件代码:
Option Explicit
'change text function date code
Private Sub Workbook_Open()
Dim yrCode As String, mnthCode As String, dyCode As String
Dim dtCode As String
Dim nM As Name
With Application
yrCode = WorksheetFunction.Rept(.International(xlYearCode), 4)
mnthCode = WorksheetFunction.Rept(.International(xlMonthCode), 2)
dyCode = WorksheetFunction.Rept(.International(xlDayCode), 2)
End With
'Can only add a name if it is absent
For Each nM In ThisWorkbook.Names
If nM.Name = "dtFormat" Then
nM.Delete
Exit For
End If
Next nM
dtCode = yrCode & mnthCode & dyCode
ThisWorkbook.Names.Add _
Name:="dtFormat", _
RefersTo:="=""" & dtCode & """", _
Visible:=False
End Sub代码确定正确的格式字符,并确保基于打开工作簿的机器正确定义dtFormat。
发布于 2022-11-25 21:22:11
使用UDF,您可以这样做:

Public Function GetFormat$(Cell As Range, Optional ByVal UseLocal As Boolean)
'get the date region settings of this computer
' https://superuser.com/questions/730371/how-to-prevent-excel-to-use-the-os-regional-settings-for-date-patterns-in-formul
' =GetFormat($A$1, TRUE)
If UseLocal Then
GetFormat = Cell.NumberFormatLocal
Else
GetFormat = Cell.NumberFormat
End If
End Function发布于 2022-11-25 21:31:10
您可以使用这样的VBA用户定义功能(UDF)来完成这一任务:

Public Function FMT$(ByVal Value, ByVal strFormat)
'used instead of the Text Function in Excel (Formula) to provide a date format which is region specific
'https://superuser.com/questions/730371/how-to-prevent-excel-to-use-the-os-regional-settings-for-date-patterns-in-formul
FMT = VBA.Format$(Value, strFormat)
End Functionhttps://stackoverflow.com/questions/74576691
复制相似问题