2015-08-04 6 views
0

Je suis un nouveau venu à VBA. J'essaie de copier la plage sélectionnée à partir de différents classeurs et collée à un classeur cible avec nom de feuille différent correspondant au nom du fichier source.Puis-je utiliser une variable comme nom de feuille (VBA)?

Le code ci-dessous:

'open file 

Sub RstChk() 
Dim StrFileName As String 
Dim StrFilePath As String 
Dim TimeStr As String 
Dim Version As Integer 
Dim x As Workbook 
Dim y As Workbook 
Dim PstTgt As String 

'define filename as array 

Dim FN(10) As String 

FN(1) = "CIO Wholesale" 
FN(2) = "RMG" 
FN(3) = "DCM" 
FN(4) = "DivHeadOth" 
FN(5) = "Runoff" 
FN(6) = "Other Risk Subs" 
FN(7) = "FIC" 
FN(8) = "Treasury" 
FN(9) = "Cash Equities" 
FN(10) = "Global Derivatives" 

'define file path 

StrFilePath = "V:\RISKMIS\PUBLIC\apps\MORNING\RMU 1.5 Report\Consolidated\" 

'define TimeStr 

TimeStr = Format(Now() - 1, "mm-dd-yyyy") 

Set y = Workbooks.Open("H:\Eform\Report_checking.xls") 

'applying filename from array using loop 
'---------------------------------------------------------------- 
For i = 1 To 10 

'define changing file name with path & loop 

For Version = 65 To 68 

StrFileName = (StrFilePath & FN(i) & "_" & TimeStr & "_" & Chr(Version) & ".xls") 

Set x = Workbooks.Open(StrFileName) 

'------------------------------------------------- 
If Chr(Version) = "A" Then 
PstTgt = "A3" 

ElseIf Chr(Version) = "B" Then 
PstTgt = "E3" 


ElseIf Chr(Version) = "C" Then 
PstTgt = "I3" 

Else 

PstTgt = "M3" 

End If 

'copy the column and paste to report checking 

y.Worksheets(FN(i)).PstTgt.Copy Destination = x.Sheets("Risk Summary").Range ("AA5:AC118") 


Application.CutCopyMode = False 

x.Close 

Next Version 

Next i 

End Sub 

Je reçois une erreur lorsque je tente de copier la plage de fichier source (x) fichier cible (Y).

Erreur d'exécution '13', incompatibilité de type

Tout ne peut pas comprendre ce qui a mal tourné.

Merci beaucoup pour votre aide.

Dan

Répondre

0

Vous avez cette erreur, car la variable PstTgt est une chaîne et non une gamme « incompatibilité de type »

Si vous regardez la documentation de Range.Copy https://msdn.microsoft.com/en-us/library/office/ff837760.aspx

Vous avez deux choix:

  • Faire PstTgt faire une gamme et se référant directement à la gamme dans votre endif

    ' Redefine PstTgt as a range 
    dim PstTgt as Range 
    
    ' set value of PstTgt 
    If Chr(Version) = "A" Then 
        set PstTgt = y.Worksheets(FN(i)).Range("A3") 
    endif 
    ... 
    ' Copy the range where you want 
    PstTgt.Copy destination:=x.Sheets("Risk Summary").Range("AA5") 
    
  • Vous gardez votre code comme ça et juste corriger votre copie en ajoutant Range

    y.Worksheets(FN(i)).Range(PstTgt).Copy Destination = x.Sheets("Risk Summary").Range("AA5")