2012-01-31 40 views
0

我需要查询数据库表,然后将3个4字段写入Excel电子表格。一旦写好这一行,我需要将'sentback'字段更新为'Y'。这是where子句中使用的最初字段。因此,整个想法是查询,写入和更改为标记为'Y',所以我不再选择这些记录。访问Excel导出更新特定字段在做时

我有一半的代码在这里工作。我知道我可以以某种方式使用DoCmd,但不能完全弄明白。

其他记录可以在例程运行期间添加到数据库中,因此更新必须发生在do中使用的当前记录集上,以避免在可能未发送的记录上设置标志。

任何帮助是极大的赞赏

Dim strSQL As String 



strExcelFile = "C:\MySpreadSheet.xls" 
strWorksheet = "WorkSheet1" 
strDB = "C:\track.accdb" 
strTable = "manifests2" 

Set db = CurrentDb 

'If excel file already exists, you can delete it here 
If Dir(strExcelFile) <> "" Then Kill strExcelFile 


strSQL = "SELECT manifests2.[Shipment ID], manifests2.[Courier Service Level],  manifests2.[Other Tracking],manifests2.[sentback] FROM " & "[" & strTable & "] WHERE (((manifests2.[sentback]) = 'N') and ((manifests2.[Other Tracking]) <> NULL))" 

Set rs = db.OpenRecordset(strSQL) 

Do While Not rs.EOF 


    rs.Edit 
    rs("sentback").Value = "Y" 
    rs.Update 

    rs.MoveNext 
Loop 

End Sub 

回答

0

如果货物ID是一个唯一的标识符,它似乎是,你可以使用Excel文件更新表,从而确保只有那些在记录该文件被标记为发送。

strExcelFile = "C:\MySpreadSheet.xls" 
'strWorksheet = "WorkSheet1" 
'strDB = "C:\track.accdb" 
strTable = "manifests2" 

Set db = CurrentDb 

''The sheet takes its name from the query. This connection string depends 
''on the versions of Access and Excel that you are using. 
cn = "[Excel 8.0;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=" & strExcelFile & "].[OutDat$]" 

''If excel file already exists, you can delete it here 
If Dir(strExcelFile) <> "" Then Kill strExcelFile 

''Just use an existing query. 
''If a query is to be created/updated each time, you need to check 
''if it exists and either create or update as appropriate. 

''strSQL = "SELECT m.[Shipment ID], m.[Courier Service Level], " _ 
     & "m.[Other Tracking], m.[sentback] " _ 
     & "FROM [" & strTable & "] As m " _ 
     & "WHERE m.[sentback] = 'N' And m.[Other Tracking] Is Not Null" 

''db.CreateQueryDef "OutDat", strSQL 

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "OutDat", strExcelFile 

strSQL = "UPDATE [" & strTable & "] SET SentBack = 'Y' " _ 
     & "WHERE [Shipment ID] In (SELECT [Shipment ID] FROM " _ 
     & cn & ")" 

db.Execute strSQL 

存在一些问题。例如,您在字段(列)名称中有空格。这会让你的生活变得更加困难。当YesNo(boolean)是更明显的选择时,您似乎选择了sentback的文本。没有什么东西等于或不等于null,东西is nullis not null

+0

太棒了!还有一个问题,是不是可以将“送回”写入excel文件,而是只写入其他3个?我想用更新声明,我知道更长时间需要在选择列回传,我可以删除?是列名。我只是使用excel文件作为链接在Access中快速设置它们,因为这是我如何接收文件。所以我将不得不找出某种导入映射宏。再次感谢你。 – user990726 2012-01-31 14:00:34

+0

是的,只需在查询设计网格中的'sentback'下的'Show'行中取消选中即可。看看'DoCmd.TransferSpreadsheet acLink' – Fionnuala 2012-01-31 14:11:44