2017-06-04 3 views
0

Ich möchte ein Excel-Blatt öffnen und Werte schreiben.Öffnen Sie eine Excel-Datei und schreiben Sie Werte in

Deshalb schrieb ich diesen

Private Sub Test() 

Dim xlApp As Object 
Dim xlWorkBook As Object 
Set xlApp = CreateObject("Excel.Application") 
xlApp.Visible = True 
Set xlWorkBook = xlApp.Workbooks.Open("C:\Users\Marc\Dropbox\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False) 
xlWorkBook.sheets(1).Range("A2").Select 

Set xlApp = Nothing 
Set xlWorkBook = Nothing 


End Sub 

alle Werke dieses. Aber die Sache ist, dass jetzt jedes Mal eine neue Excel-Datei geöffnet wird. Und ich möchte nur ein existierendes öffnen. Irgendwelche Gedanken darüber, wie man das ändert?

Antwort

1

Try this:

Sub Test() 

Dim xlApp As Object 
Dim xlWorkBook As Object 
Dim path As String 
Set xlApp = CreateObject("Excel.Application") 
xlApp.Visible = True 

path = "C:\Users\Marc\Dropbox\PROJECTEN\Lopend\office_VA\macroStore.xlsx" 
If IsFileOpen(path) Then 
    Set xlWorkBook = GetObject(path) 
Else 
    Set xlWorkBook = xlApp.Workbooks.Open(path) 
End If 

Set xlApp = Nothing 
Set xlWorkBook = Nothing 

End Sub 

Function IsFileOpen(filename As String) 
    Dim filenum As Integer, errnum As Integer 

    On Error Resume Next ' Turn error checking off. 
    filenum = FreeFile() ' Get a free file number. 
    ' Attempt to open the file and lock it. 
    Open filename For Input Lock Read As #filenum 
    Close filenum   ' Close the file. 
    errnum = Err   ' Save the error number that occurred. 
    On Error GoTo 0  ' Turn error checking back on. 

    ' Check to see which error occurred. 
    Select Case errnum 

     ' No error occurred. 
     ' File is NOT already open by another user. 
     Case 0 
     IsFileOpen = False 

     ' Error number for "Permission Denied." 
     ' File is already opened by another user. 
     Case 70 
      IsFileOpen = True 

     ' Another error occurred. 
     Case Else 
      Error errnum 
    End Select 

End Function 

Hinweis: Die Funktion wird von Microsoft site

+0

genommen Es mir den Fehler gibt, dass der Typ nicht –

+0

@Henk Straten definiert ist, ich meine Antwort bearbeitet, da Sie nicht mit Excel arbeiten VBA – Tehscript

Verwandte Themen