Excel时间格式自动更改问题

时间:2017-06-01 04:17:59

标签: sql excel excel-vba vba

我目前正在处理一个Excel应用程序,它可以从我的表单工作表中获取信息并将其显示在显示工作表中。到目前为止,数据可以完美传输,除了一个小怪癖。

单击“执行”时,“显示”工作表将显示数据 这是截图: Here is the screenshot.

在执行显示之前,表单工作表中的时间字段格式为h:mm AM / PM。但是,当我单击显示工作表中的执行时,时间格式突然在表单工作表中更改,如下所示: as seen here.

此外,格式的变化也可以在Display表中看到。我尝试将两种工作表的格式设置为相同,结果仍然相同。

它是SQL1语句的问题还是一般的编码?这是代码示例。

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ActiveWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub
ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False
End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")   ' GET LATEST RECORD
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range       'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ActiveWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ActiveWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A2:BR5000").Value = Empty
End Sub

如果有人可以提供帮助,我非常感激。

更新:

显然,这个怪癖比我想象的要大。经过更多测试后,我发现第二个摘要表也会受到影响,也可以在此处看到。 as seen here。虽然至少是下半部分。这个谜团不断堆积起来......

1 个答案:

答案 0 :(得分:0)

我认为你必须要看看NumberFormat iirc添加类似" DD / MM / YYYY"到范围(在您的情况下为列)。我在使用Office 365的Mac上,虽然VBA现在在应用程序中,但智能感知不存在,所以除非你了解Excel对象模型,否则它就是皇家PITA!