我可以使用变量作为工作表名称(VBA)

时间:2015-08-04 20:11:32

标签: vba variables naming

我是VBA的新手。我正在尝试从不同的工作簿复制选定的范围并粘贴到具有与源文件的名称相对应的不同sheetname的目标工作簿。

代码如下:

'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

当我尝试将范围从源文件(x)复制到目标文件(Y)时出现错误。

  

运行时错误'13',输入不匹配

无法弄清楚出了什么问题。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您收到此错误是因为您的变量PstTgt是字符串而不是范围“类型不匹配”

如果您查看Range.Copy https://msdn.microsoft.com/en-us/library/office/ff837760.aspx

的文档

您有两种选择:

  • 设置PstTgt范围并直接引用您的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")
    
  • 您可以保留代码,只需添加范围

    即可更正您的副本
    y.Worksheets(FN(i)).Range(PstTgt).Copy Destination = x.Sheets("Risk Summary").Range("AA5")