最初工作后未设置对象变量或块变量

时间:2015-07-10 14:11:05

标签: excel vba ms-access

我有这个非常令人沮丧的问题。下面的代码应该从Access导出查询到Excel,然后为第一行着色,加粗并自动调整整个工作表。

这需要多次发生,因此我只需复制粘贴所需的次数,并对昏暗名称进行少量更改。不幸的是,它在第​​二轮之后停止工作并且给了我错误"对象变量或者没有设置块变量"然后它突出显示代码的一部分,如下所示。我的意思是,在这一点上,我只是手动执行此操作,因此这不是一个危及生命的问题,但我很想知道如何使这项工作。

谢谢,这里有多次重复的代码:

Private Sub cmdFinal_Click()
Dim fileLocation As String ' Main folder
Dim finalExport As String

fileLocation = "C:\MYDOCS\Latest\"
finalExport = "FINAL_EXPORT_" & UCase(Format(DateAdd("m", -7, Date), "MMMyy")) & "-" & UCase(Format(DateAdd("m", -2, Date), "MMMyy"))

' Export queries to Final Excel file
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qryFINAL", fileLocation & finalExport True, finalExport 
        DoEvents
        Me.ProgressBar.Visible = True
        Me.ProgressBar.Width = 500
        Me.Repaint
        DoEvents
    ' Open Excel file, apply colors, save, and quit
    Set xl = CreateObject("Excel.Application")
    Set wr = xl.Workbooks.Open(fileLocation & finalExport & ".XLSX")
    Call ColorMe
    DoEvents
    wr.Save
    wr.Close
    xl.Quit
    DoEvents
    Set sh = Nothing
    Set wr = Nothing
    Set xl = Nothing
    DoEvents

Sub ColorMe()
'
' Format document and make it pretty
'
Set sh = wr.Worksheets(1)

With sh
    sh.Rows("1:1").EntireRow.Select
    With Selection.Interior   <----------Here's where the error occurs
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.499984740745262
        .PatternTintAndShade = 0
    End With
    With Selection.Font
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = 0
    End With
End With
    Selection.Font.Bold = True
    Cells.Select
    Cells.EntireColumn.AutoFit
DoEvents
End Sub

1 个答案:

答案 0 :(得分:3)

有几件事:

1)我无法看到方法cmdFinal_Click()关闭的位置 - 没有

End Sub

线。

2)您应该将变量wr作为参数传递给ColorMe方法。否则,此方法不知道要处理的工作簿:

Sub ColorMe(wr As Excel.Workbook)

Call ColorMe(wr)

3)您无需选择范围即可对其进行格式化。请尝试以下代码:

Sub ColorMe(wr As Excel.Workbook)
    Dim sh As Worksheet
    Dim rng As Excel.Range


    Set sh = wr.Worksheets(1)
    Set rng = sh.Rows(1)   '<---- you create reference to the first row here
                           '      and later you should use this variable
                           '      instead of selecting cells in Worksheet and
                           '      use Selection.

    With rng.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = -0.499984740745262
        .PatternTintAndShade = 0
    End With
    With rng.Font
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = 0
        .Bold = True
    End With

    'Cells.Select           '<---- Commented. Can cause errors if worksheet is not active.
    Cells.EntireColumn.AutoFit

    DoEvents

End Sub