0
Sub openwb()

Dim sb As String

ChDir "E:\sarath\PTMetrics"

Workbooks.Open ("E:\sarath\PTMetrics\D8 L538-L550_16MY_Powertrain Metrics_" & (Format(Date, "YYYYMMDD") - 1) & ".xlsm")

ActiveWorkbook.SaveAs "E:\sarath\PTMetrics\D8 L538-L550_16MY_Powertrain Metrics_" & (Format(Date, "YYYYMMDD") & ".xlsm")

Set x260wb = ActiveWorkbook

Debug.Print x260wb.Name

Workbooks("x260wb").Sheets("All Concerns").Range(A1).Value = "Hay..."

End Sub

在第 8 行,我收到错误消息“下标超出范围”。你能帮忙吗?...

4

1 回答 1

0

勺子最后一次喂你:)

  1. 声明你的对象/变量。如果您使用它们,工作会变得容易得多。避免使用ActiveWorkbook/ActiveSheet/Selection..etc.. 有趣的阅读
  2. 变量和字符串是有区别的。适当地使用它们。如果您将变量名包含在其中,"则它们将变为字符串,反之亦然,即如果字符串是一个单词。
  3. 您正在从 string 中减去 1 Format(Date, "YYYYMMDD") - 1Format返回一个String。请参阅我在下面的代码中给出的替代方案。
  4. 在 Excel VBA 中执行Save As时,您必须指定FileFormat例如 xlsm 的文件格式为 53 以下是其他文件格式。

文件格式

50 = xlExcel12 (Excel Binary Workbook in 2007-2013 with or without macro's, xlsb)
51 = xlOpenXMLWorkbook (without macro's in 2007-2013, xlsx)
52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2013, xlsm)
56 = xlExcel8 (97-2003 format in Excel 2007-2013, xls)

您的代码(未测试)

Sub openwb()
    Dim wb As Workbook
    Dim sPath As String, sFilename As String, newName As String

    sPath = "E:\sarath\PTMetrics\"
            sFilename = sPath & _
                "D8 L538-L550_16MY_Powertrain Metrics_" & _
                Format(Date - 1, "YYYYMMDD") & _
                ".xlsm"

    Set wb = Workbooks.Open(sFilename)

    newName = sPath & _
              "D8 L538-L550_16MY_Powertrain Metrics_" & _
              Format(Date, "YYYYMMDD") & _
               ".xlsm"

    wb.SaveAs newName, FileFormat:=53

    wb.Sheets("All Concerns").Range("A1").Value = "Hay..."
End Sub
于 2013-10-04T10:16:33.227 回答