2016-10-28 11 views
-4

Ref: Access "Compact and Repair" programaticallyMS Access Jet Database Programatically компактные

HI Ребята, я ищу способ запуска пакетного сценария с помощью запланированного задания для сжатия и или отремонтировать «Jet» .mdb файл/базу данных.


Environment
Win 7 32 бит
Jet формат 4.x
application.exe Оригинальный язык Код неизвестен


у меня установлен реактивный двигатель - но позволяет делать вид, что это не так запрос сценария

Автоматика - это конечная игра здесь.

Я прочитал Упомянутый ссылку Поул «Access "Compact and Repair" programatically»

Я действительно не кодер - так я провожу около 2-3 часов, пытаясь сделать все, что работа, я с треском провалились. : (

Моя просьба - если вы можете помочь, пожалуйста я нужен полный «копию и прошлый код» - мои пальцы страдают от Dyslexiconica;). Я просто не могу код на этом уровне.

Я могу сделать простой командный файл успешно. Меня не волнует, что это VBA или прямая командная строка, но вам нужно научить меня, как заставить ее работать.

Спасибо за любую помощь.

С наилучшими пожеланиями, Винсент

+0

Извините, но Stackoverflow не является услугой написания кода - пожалуйста, держать вопросы [по теме] (http://stackoverflow.com/help/on-topic) и рассмотреть вопрос об обращении на более подходящий [Stack Exchange, сайт ] (HTTP: // СТО ckexchange.com/sites) – David

ответ

0

Вот Jazzed до версии компакта на закрытии, в котором отображаются сообщения для общих проблем; например, когда исходный файл не существует; когда исходный файл имеет недопустимое расширение имени файла; и когда файл назначения существует (он не должен).

Option Compare Database 
Option Explicit 

' Declare an enumeration of long integer 
' constants, to be used as the return values 
' for the RepairDatabase() function. 
' As Access's CompactRepair() method returns 
' TRUE or FALSE, the Enum uses -1 (TRUE) for 
' success and 0 for failure. 
Public Enum ryCompactResult 
    cmpCompactSuccessful = -1 
    cmpCompactFailed = 0 
    cmpErrorOccurred = 1 
    cmpSourceFileDoesNotExist = 2 
    cmpInvalidSourceFileNameExtension = 3 
    cmpDestinationFileExists = 4 
End Enum 


Private Sub TestRepair() 

    Dim strSource As String 
    Dim strDestination As String 
    Dim lngRetVal As ryCompactResult 

    strSource = "C:\MyFolder\db1.mdb" 
    strDestination = "C:\MyFolder\db2.mdb" 

    ' Call the function: 
    lngRetVal = RepairDatabase(strSource, strDestination) 

    ' Examine the return value from the function 
    ' and display appropriate message: 
    Select Case lngRetVal 

    Case cmpCompactSuccessful 
     MsgBox "Compact & repair successful.", _ 
      vbOKOnly + vbInformation, _ 
      "Program Information" 

    Case cmpSourceFileDoesNotExist 
     MsgBox strSource & vbNewLine & vbNewLine _ 
      & "The above file does not exist.", _ 
      vbOKOnly + vbExclamation, _ 
      "Program Finished" 

    Case cmpInvalidSourceFileNameExtension 
     MsgBox strSource & vbNewLine & vbNewLine _ 
      & "The above file has an invalid filename " _ 
      & "extension.", vbOKOnly + vbExclamation, _ 
      "Program Finished" 

    Case cmpDestinationFileExists 
     MsgBox strDestination & vbNewLine & vbNewLine _ 
      & "The above destination file exists. " _ 
      & vbNewLine _ 
      & "Please delete the above file or " _ 
      & "use a different destination filename.", _ 
      vbOKOnly + vbExclamation, "Program Finished" 

    Case cmpErrorOccurred 
     ' The RepairDatabase() function has 
     ' already displayed an error message. 

    End Select 


End Sub 

Function RepairDatabase(_ 
    strSource As String, _ 
    strDestination As String) As ryCompactResult 

    ' IN: 
    ' 
    ' strSource: 
    '  The full path to the database that is 
    '  to be compacted. 
    ' 
    ' strDestination: 
    '  The full path to the resultant database 
    '  after strSource has been compacted. 
    ' 
    ' OUT: 
    ' 
    ' This function returns one of the values in 
    ' the ryCompactResult Enum. 


    Dim lngRetVal As ryCompactResult 
    Dim strFileName As String 
    Dim strFileNameExtn As String 
    Dim lngPos As Long 


On Error GoTo Error_RepairDatabase 

    ' See if source file exists: 
    strFileName = Dir(strSource) 
    If Len(strFileName) = 0 Then 
     lngRetVal = cmpSourceFileDoesNotExist 
     GoTo Exit_RepairDatabase 
    End If 

    ' See if source filename has appropriate 
    ' filename extension (mdb or accdb). 
    ' First, see if filename contains a period: 
    lngPos = InStr(strFileName, ".") 
    If lngPos = 0 Then 
     ' Period not found in filename; 
     ' i.e. no filename extension found. 
     lngRetVal = cmpInvalidSourceFileNameExtension 
     GoTo Exit_RepairDatabase 
    Else 
     ' Get filename extension: 
     strFileNameExtn = Mid(strFileName, lngPos + 1) 
     strFileNameExtn = LCase(strFileNameExtn) 

     Select Case strFileNameExtn 
     Case "mdb", "accdb" 
      ' Correct filename extension found. 
      ' We can proceed with compact & repair. 
     Case Else 
      ' Invalid filename extension found. 
      lngRetVal = cmpInvalidSourceFileNameExtension 
      GoTo Exit_RepairDatabase 
     End Select 
    End If 

    ' Destination file must not exist: 
    strFileName = Dir(strDestination) 
    If Len(strFileName) > 0 Then 
     lngRetVal = cmpDestinationFileExists 
     GoTo Exit_RepairDatabase 
    End If 

    ' Compact and repair database: 
    lngRetVal = Application.CompactRepair(_ 
       strSource, strDestination, True) 

Exit_RepairDatabase: 

    RepairDatabase = lngRetVal 
    Exit Function 

Error_RepairDatabase: 

    lngRetVal = cmpErrorOccurred 
    MsgBox "Error No: " & Err.Number _ 
     & vbNewLine & vbNewLine _ 
     & Err.Description, _ 
     vbOKOnly + vbExclamation, _ 
     "Error Information" 

    Resume Exit_RepairDatabase 

End Function 

Вот еще один компактный/функция ремонта ниже, но не рекомендуется делать произвольно на каждый близко - просто заменить/удалить мой на код ошибки с собственным

Function RepairDatabase(strSource As String, _ 
     strDestination As String) As Boolean 
     ' Input values: the paths and file names of 
     ' the source and destination files. 

Dim strSource As String 
Dim strDestination As String 

strSource = "\\Dg\Debt \2010\Summary\Summary.mdb" 
strDestination = "\\Dg\Debt \2010\Summary\Summary_Compact.mdb" 

    ' Trap for errors. 
    On Error GoTo ErrorRoutine 

    ' Compact and repair the database. Use the return value of 
    ' the CompactRepair method to determine if the file was 
    ' successfully compacted. 
    RepairDatabase = _ 
     Application.CompactRepair(_ 
     LogFile:=True, _ 
     SourceFile:=strSource, _ 
     DestinationFile:=strDestination) 

    ' Reset the error trap and exit the function. 
    On Error GoTo 0 
    Exit Function 

' Return False if an error occurs. 
Exit_Function: 
    Exit Function 
ErrorRoutine: 
    RepairDatabase = False 
    Call LogError(Err.Number, Err.Description, conMod & ".RepairDatabase", , True) 
    Resume Exit_Function 
End Function 

Call the function as such: 
Call RepairDatabase(strSource, strDestination) 

Вызвать функцию как таковую:

Call RepairDatabase(strSource, strDestination) 
+0

Большое спасибо. Я проверю это. С наилучшими пожеланиями, –