2016-03-15 21 views
5

Amici, Sto tentando di aprire un file CSV (generato quotidianamente da un altro programma) ogni giorno e copiare i dati nel foglio CSV in un determinato foglio nella cartella di lavoro corrente. Ho lavorato su questo codice per un po 'e penso che sia davvero vicino a essere nel giusto, ma continuo a ricevere un errore di run-time 438 sulla mia linea di copia/incolla. Qualsiasi aiuto?Apri CSV e copia

Grazie!

Ecco il mio codice:

Sub GetCSV() 

Dim thatWB As Workbook, thisWB As Workbook 
Dim thisWS As Worksheet, thatWS As Worksheet 
Dim zOpenFileName As String 
Dim inputData As String 

'get name of sheet to open 
inputData = InputBox("Enter name of file") 

'open CSV file 
zOpenFileName = Application.GetOpenFilename 

'error handling 
If zOpenFileName = "" Then Exit Sub 

Application.ScreenUpdating = False 

Set thisWB = ThisWorkbook 'destination workbook 
Set thisWS = Sheets("f_dump") 'destination worksheet 

Set thatWB = Workbooks.Open(zOpenFileName) 'source CSV 
Set thatWS = thatWB.Sheets(inputData) 'source worksheet 

Application.CutCopyMode = False 

thatWB.thatWS.Range("A1:G150").Copy Destination:=thisWB.thisWS.Range("A1") 

thatWB.Close 

End Sub 

risposta

4

Provate a guardare a questo. Ho rimosso questo WB e ThatWB dalla tua copia e incolla parte del codice, perché era la fonte del primo problema (e ho spostato le specifiche della cartella di lavoro nella dichiarazione del foglio).

Quindi il prossimo numero era con Paste. Im non so perché, ma quando si chiama in serie, è necessario utilizzare PasteSpecial (VBA in Excel è una magia po 'al posto di programmazione/scripting)

Sub GetCSV() 

Dim thatWB As Workbook, thisWB As Workbook 
Dim thisWS As Worksheet, thatWS As Worksheet 
Dim zOpenFileName As String 
Dim inputData As String 

'get name of sheet to open 
inputData = InputBox("Enter name of file") 

'open CSV file 
zOpenFileName = Application.GetOpenFilename 

'error handling 
If zOpenFileName = "" Then Exit Sub 

Application.ScreenUpdating = False 

Set thisWB = ThisWorkbook 'destination workbook 
Set thisWS = ThisWorkbook.Sheets("Sheet1") 'destination worksheet 

Set thatWB = Workbooks.Open(zOpenFileName) 'source CSV 
Set thatWS = thatWB.Sheets(inputData) 'source worksheet 

Application.CutCopyMode = False 

thatWS.Range("A1:G150").Copy 
thisWS.Range("A1:G150").PasteSpecial xlPasteAll 
thatWB.Close 

End Sub 
+2

mentre il parentaging si parla qui è corretto, la copia diretta sarà anche funziona bene, prova questa linea: 'thatWS.Range (" A1: G150 "). Copy Destination: = thisWS.Range (" A1 ")' Per essere chiari, funzionerà anche il metodo 'PasteSpecial'. Non è solo necessario. –

+0

Grazie a entrambi. Entrambe le soluzioni funzionano correttamente. Ho segnato Lubos come corretto, ma quello di Scott funziona altrettanto bene. – tulanejosh