如何将字符串转换为工作簿名称

时间:2013-10-02 10:07:42

标签: excel-vba vba excel

Sub openwb()

Dim x260path As String

x260path = "E:\sarath\PTMetrics\20131002\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_" & Format(Date, "YYYYMMDD") - 1

Workbooks("x260path").Activate

ActiveWorkbook.SaveAs ["E:\sarath\PTMetrics\20131002\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_" & Format(Date, "YYYYMMDD")]

Debug.Print x260path

End Sub

这里,当我执行时,错误显示“下标超出范围”。并且它出现在第4行。当我使用'workbook'来声明'x260path'而不是字符串时,它在第3行显示另一个错误“对象变量或块变量未设置”。你可以帮忙吗?为什么会这样?

1 个答案:

答案 0 :(得分:0)

要激活工作簿,您需要设置对工作簿名称的引用,而不是工作簿的完整路径&名称。因此,在x260path变量中,您只需要获取名称。有几种可能的方法可以做到这一点。这是我刚才想到的:

Dim x260path As String

x260path = "E:\sarath\PTMetrics\20131002\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_" & Format(Date, "YYYYMMDD") - 1

Dim x260name As String
x260name = Split(x260path, "\")(UBound(Split(x260path, "\")))

Workbooks(x260name).Activate

'the rest of your code here