有没有一种方法可以在Excel VBA中创建范围的并集?

时间:2019-09-23 12:32:57

标签: excel vba range union

我正在尝试通过将范围合并到一个变量中来提高代码效率,然后将其用于将函数插入所有合并的范围中。由于某种原因,无论我尝试什么,最终都会产生错误。我目前正在尝试联合方法,但始终收到“必需的对象”或“对象全局的方法范围已失败”的错误消息。有人可以帮忙解决我的问题吗?

私人子目录(sXLFile,sFile,scell)

Workbooks.OpenText Filename:= _
    sFile, _
    Origin:=xlWindows, StartRow:=1, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), _
    Array(1, 1), Array(2, 1), Array(5, 1), Array(6, 1), Array(8, 1), Array(9, 1), _
    Array(10, 1), Array(11, 1), Array(14, 1), Array(16, 1), Array(23, 1), Array(26, 1), _
    Array(30, 1), Array(45, 1), Array(60, 1), Array(75, 1), Array(90, 1), _
    Array(105, 1), Array(120, 1), Array(135, 1), Array(150, 1), Array(165, 1), _
    Array(180, 1), Array(195, 1), Array(210, 1), Array(225, 1), Array(240, 1), _
    Array(255, 1), Array(270, 1), Array(285, 1), Array(300, 1), Array(315, 1), _
    Array(330, 1), Array(345, 1), Array(360, 1), Array(375, 1), Array(390, 1))

Set sxlFile1 = ActiveWorkbook

iRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
iCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

Set CopyFrom = sxlFile1.Sheets(Replace(scell, ".txt", "")).Range(Cells(1, 1), Cells(iRow, iCol))
Set CopyTo = sXLFile.Sheets("Contct").Range("A6")

CopyFrom.Copy CopyTo

With sXLFile.Sheets("Contct")
    .Activate
    With .Range("A6", Cells(iRow + 5, iCol))
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .NumberFormat = "General"
    End With
    .Range("M6:M" & iRow + 5).FormulaR1C1 = _
        "=CONCATENATE(RC[-12],RC[-11],TEXT(RC[-10],""000""),RC[-9],RC[-8],RC[-7],RC[-6],RC[-5],TEXT(RC[-4],""000""),TEXT(RC[-3],""00""),RC[-2],RC[-1])"

    Set rs = .Range(Cells(6, 16), Cells(iRow + 5, 16)): rv = .Range(Cells(6, 22), Cells(iRow + 5, 22)): ry = .Range(Cells(6, 25), Cells(iRow + 5, 25)): rab = .Range(Cells(6, 28), Cells(iRow + 5, 28)): rae = .Range(Cells(6, 31), Cells(iRow + 5, 31)): rah = .Range(Cells(6, 34), Cells(iRow + 5, 34)): _
        rak = .Range(Cells(6, 37), Cells(iRow + 5, 37)): rngUnion = .Union(rs, rv, ry, rab, rae, rah, rak)
    .Range("P6:P" & iRow + 5).FormulaR1C1 = _
        "=ABS(RC[-2]-RC[-1])"
    .Range(rngUnion).FormulaR1C1 = _
        .Range("P6:P" & iRow + 5).FormulaR1C1


End With

Windows(scell).Close SaveChanges:=False

0 个答案:

没有答案