Excel VBA范围variables引发错误1004 – 我在

我需要你的帮助。 我是新的使用范围作为variables,所以可能有一些明显的我失踪,但似乎无法find一个解决scheme后,大量的谷歌search。

我格式化四张数据(标题,漂亮的填充颜色,漂亮的边框)。 他们几乎都是一样的,但他们有不同数量的列。 为了节省重复的代码,我写了一个过程来完成格式化,另一个过程来改变variables并调用格式化代码。

调用代码示例:

' Set Customer detail variables. varGlobalID = Sheets(varWST1Dockets).Cells(2, 13).Value varCustomerName = Sheets(varWST1Dockets).Cells(2, 14).Value 

格式暂停

 ' Set Variables varReportHeading = "Suspended Dockets Investigation" Set rngDataHeadings = Range("B11", "T11") Range("B1048576").End(xlUp).Select Set rngDataTable = Range(Selection, "T11") Range("B1048576").End(xlUp).Select Set rngData = Range(Selection, "T12") ' Run Format Reports Procedure Sheets(varWSSuspended).Select Call FormatReports 

格式化代码示例

 ' Format Data Headings rngDataHeadings.Select With Selection.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = -4300032 .PatternTintAndShade = 0 End With With Selection.Font .ColorIndex = 2 .TintAndShade = 0 .Bold = True End With With Selection .HorizontalAlignment = xlLeft .VerticalAlignment = xlCenter .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With 

“申请边界

 rngDataTable.Select With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 2 .TintAndShade = 0 .Weight = xlMedium End With 

代码似乎在variables的第一次运行,但不是第二次。 我需要在重置之前卸载它们吗? 还是我在做别的愚蠢明显的错误?

提前致谢。

Set rngDataHeadings = Range("B11", "T11")引用ActiveSheet的B11:T11 。 select另一个工作表,并尝试rngDataHeadings.Select将引发exception运行时错误'1004'select方法的范围类失败

最好避免select和激活。 你应该看select单元格(范围,单元格,活动单元格,结束,偏移)

如果你有标准表,这将工作。

 Sub FormatTable(wsWorksheet As Worksheet, HeaderAddress As String) Dim rDataBody As Range Dim rHeader As Range With wsWorksheet Set rHeader = .Range(HeaderAddress, .Range(HeaderAddress).End(xlToRight)) Set rDataBody = Range(HeaderAddress).CurrentRegion Set rDataBody = rDataBody.Offset(1).Resize(rDataBody.Rows.Count - 1) End With With rHeader.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = -4300032 .PatternTintAndShade = 0 End With With rHeader.Font .ColorIndex = 2 .TintAndShade = 0 .Bold = True End With With rHeader .HorizontalAlignment = xlLeft .VerticalAlignment = xlCenter .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With ' Apply Borders With rDataBody.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 2 .TintAndShade = 0 .Weight = xlMedium End With End Sub 

像这样称呼它

FormatTable工作表(“Sheet1”),“B11”