2017-04-11 61 views
0

移動工作臺我有一個現有的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

只要改變「31」到「11」和一個參考到「32」的所有出現「12」 – Variatus

+0

可以不是那樣的改變,在列中的數字贏得」直到小區12到小區32出現 –

回答

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...