通过修复vba代码移动表

时间:2017-04-11 09:34:48

标签: excel vba excel-vba

我有一个现有的VBA代码如下:

Sub fillDL()
    Dim cn As Object, lr As Integer, soct As Integer, i As Integer
    lr = Range("P31").End(xlDown).Row
    If lr > 32 Then Rows("32:" & lr - 1).Delete Shift:=xlUp
    Range("AO1").Formula = "=COUNTA(AN:AN)"
    soct = Range("AO1").Value + 31
    If soct > 31 Then
        Rows("32:" & soct).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        Set cn = CreateObject("ADODB.Connection")
        cn.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";")
        Range("A32").CopyFromRecordset cn.Execute("select b.f4, b.f5, b.f6, b.f7, '','','','','','','', '','','','','','', b.f9, b.f10,'','','','', b.f12,'','','','', b.f13,'','','','',b.f14 " & _
                                                    "from [BILL$AN1:AN] a inner join [pivot$A6:N] b on a.f1 = b.f1 where a.f1 is not null")"

因为它是从第31行开始编写的,但现在我需要将表从第31行移到第11行。你们可以帮我修复这个VBA吗

1 个答案:

答案 0 :(得分:0)

将来,为了让您自己更灵活地使用代码,您应该添加Const RowNum As Long = 11,并在Sub内使用对RowNum的引用。这样,如果将来你想要修改到第150行(或其他),你可以在一个地方修改它。

<强>代码

Option Explicit

Const RowNum    As Long = 11

Sub fillDL()

    Dim cn As Object, lr As Long, soct As Long, i As Long

    lr = Range("P" & RowNum).End(xlDown).Row

    If lr > RowNum + 1 Then Rows(RowNum + 1 & ":" & lr - 1).Delete Shift:=xlUp

    Range("AO1").Formula = "=COUNTA(AN:AN)"
    soct = Range("AO1").Value + RowNum
    If soct > RowNum Then
        Rows(RowNum + 1 & ":" & soct).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        ' rest of your code...