Excel VBA范围变量引发错误1004 - 我在

时间:2016-07-29 02:39:20

标签: excel vba excel-vba

我需要你的帮助。我不习惯使用范围作为变量,所以可能有一些显而易见的遗漏,但我似乎无法在大量谷歌搜索后找到解决方案。

我正在格式化四张数据(标题,漂亮的填充颜色,漂亮的边框)。它们几乎都是一样的,但它们的列数不尽相同。为了保存重复的代码,我编写了一个程序来进行格式化,另一个程序来更改变量并调用格式代码。

调用代码示例:

' 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

代码似乎适用于第一次运行变量而不是第二次运行。在重置之前我需要卸载它们吗?或者我在做其他愚蠢的事情显然是错的?

提前致谢。

1 个答案:

答案 0 :(得分:1)

B11:T11引用ActiveSheet的rngDataHeadings.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 将抛出异常运行时错误'1004'选择Range类失败的方法

最好避免选择和激活。您应该观看Selecting Cells (Range, Cells, Activecell, End, Offset)

如果你有标准表,这将有效。

String Extraction="cmd.exe /c start C:\\task\\Extracting.bat "; 
//Runtime.getRuntime().exec(Extraction);

final Process p = new ProcessBuilder("cmd.exe", "/c", "start /WAIT C:\\task\\Extracting.bat").redirectErrorStream(true).start();
p.waitFor();
System.out.println("Job done!!");

像这样称呼

  

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