2017-06-06 89 views
-1

我是编程/编码新手,我的代码出现问题。VBA/Excel中的外部过程和语法无效

我目前正试图在excel中编写一个宏,该宏将通过excel文档并在重复列上插入部分空白行。

我目前使用Excel 2010中

因此,举例来说,如果Excel工作表中包含:

Column A, Column B, Column C, Column D, Column E 
     1  Apples  1  40  Blue 
     1 Bananas  2  50  Red 
     1 Oranges  3  60  Pink 
     2 Cherries   
     3  Kiwis   

然后脚本将其分类到:

Column A, Column B, Column C, Column D, Column E 
     1  Apples  1  40  Blue 
     1 Bananas   
     1 Oranges   
     2 Cherries  2  50  Red 
     3  Kiwis  3  60  Pink 

因此对数据进行排序通过列A和C,同时还在C,D和E中创建空格(如果列A中的值不等于列C中的值)。

我迄今为止代码:

Sub Main() 
Dim a As Long, c As Long 
Dim objRange As Range 
Dim strCIDCol1 As String, strCIDCol3 As String 

a = 1 'row counter for Column A 
c = 1 'row counter for Column C 

Do Until ActiveSheet.Cells(a, 1) = "" 
    'sets the loop to run until A1 is blank 
    strCIDCol1 = ActiveSheet.Cells(a, 1) 
     'sets the value of A1 as CIDCol1 
    strCIDCol3 = ActiveSheet.Cells(c, 3) 
     'sets the value of C1 as CIDCol3 
    If (strCIDCol1 <> strCIDCol2) Then 
     'runs until A(a) and C(c) are not equal 
     Set objRange = ActiveSheet.Cells(c, 3).Range(Cells(c, 3), Cells(c, 5)) 
     objRange.Activate 
      'Selects Columns C, D, and E 
     objRange.Insert (xlShiftDown) 
      'Inserts "Shift Row Down" 
     strCIDCol1 = ActiveSheet.Cells(a + 1, 1) 
      'moves on 
    End If 
    a = a + 1 'adds 1 to counter to move to next row 
    c = c + 1 'adds 1 to counter to move to next row 
Loop 
End Sub 

我不断收到关于

a = 1 
c = 1 

a = a + 1 
c = c + 1 

我还得到一个1004错误 “无效的外部程序” 错误“插入范围级失败的方法“

objRange.Insert (xlShiftDown) 

我不知道我在做什么与objRange。我在网上看到了这些代码,并试图调整它以适应我需要的内容。解释的方式是,在这种情况下,objRange用于突出显示选定区域列C,D和E.然后,Insert会通过在突出显示的单元格上插入一行来移动单元格。

+0

//未在VBA中使用进行评论。用//替换为' – RADO

+1

@Tony什么是'objExcel'。看起来这是你的代码的一部分,我敢打赌,错误是由你现在不显示的东西触发的。 – Masoud

+1

方便的提示:不要使用Integer进行行计数,因为它们只能保存带符号的16位值(最大值为32767)。改用Long。 –

回答

0
If (strCIDCol1 <> strCIDCol2) Then 

您从未定义过strCIDCoL2。我认为你的意思是str CIDCol3在这里。

Set objRange = ActiveSheet.Cells(c, 3).Range(Cells(c, 3), Cells(c, 5)) 

这是设置范围的错误语法。尝试使用:

Set objRange = Range(ActiveSheet.Cells(c,3).Range(Cells(c,3), Cells(c,5))) 

您是否确定要使用objRange.activate而不是objRange.select?