Excel VBA:自动填充动态范围错误

时间:2014-02-18 09:49:15

标签: excel vba autofill

我正在编写小代码来自动完成我的一些工作。我正在使用Autofill来填补范围。只要范围保持不变,一切正常。当我更改范围时,它显示错误1004:此操作要求合并的单元格大小相同。

还要补充一点,它只会在范围变大时显示。

以下是我的代码的一部分,当'autofill first column下面的范围更改行变为黄色时:

Dim WSL As Worksheet, WSB As Worksheet
Dim first_col As Long, second_col As Long
Dim first_r As Byte, first_c As Byte
Dim second_r As Byte, second_c As Byte
Dim LastCellRowNumber As Long
Dim LastCell As Range, ActiveWS As String

Application.ScreenUpdating = False

Set WSB = Worksheets("Barcodes") 'your worksheet name
Set WSL = Worksheets("List") 'your worksheet name
With WSL
    Set LastCell = .Cells(.Rows.Count, "A").End(xlUp)
    LastCellRowNumber = LastCell.Row
End With

ActiveWS = ActiveSheet.Name

first_col = Round(LastCellRowNumber / 2) + 1
second_col = LastCellRowNumber - first_col

first_r = 5 'position of "first column" row
first_c = 7 'position of "first column" column
second_r = 5 'position of "second column" row
second_c = 11 'position of "first column" column

j = 7
k = 8
l = 7
m = 8

'activate Barcodes sheet
WSB.Activate

'autofill first column
WSB.Range(Cells(first_r, first_c), Cells(first_r + 1, first_c)).AutoFill _
Destination:=Range(Cells(first_r, first_c), Cells((first_r + 1) + (first_col * 2) - 4, _
first_c)), Type:=xlFillDefault 'filling column G

WSB.Range(Cells(first_r, first_c + 1), Cells(first_r + 1, first_c + 2)).AutoFill _
Destination:=Range(Cells(first_r, first_c + 1), Cells(first_r + 1 + (first_col * 2) - 4, _
first_c + 2)), Type:=xlFillFormats 'filling with columns H:I

'autofill second column
WSB.Range(Cells(second_r, second_c), Cells(second_r + 1, second_c)).AutoFill _
Destination:=Range(Cells(second_r, second_c), Cells(second_r + 1 + (second_col * 2), _
second_c)), Type:=xlFillDefault 'filling column K

WSB.Range(Cells(second_r, second_c + 1), Cells(second_r + 1, second_c + 2)).AutoFill _
Destination:=Range(Cells(second_r, second_c + 1), Cells(second_r + 1 + (second_col * 2), _
second_c + 2)), Type:=xlFillFormats 'filling with columns L:M

1 个答案:

答案 0 :(得分:0)

跟进评论:

正如您的错误消息所示,您已合并具有不同“形状”的单元格。在第一行C1:D1合并,但在第二行D2:E2。我建议你首先让range("C200:D200").UnMerge取消合并目标范围内的所有单元格(第一行除外)。

这样的事情应该有用(只适合你的范围来纠正一个)

With wbs
    'unmerge all cells
    .Range(.Cells(first_r + 1, first_c), .Cells((first_r + 1) + (first_col * 2) - 4, _
        first_c)).UnMerge

    'autofill first column
    .Range(.Cells(first_r, first_c), .Cells(first_r + 1, first_c)).AutoFill _
    Destination:=.Range(.Cells(first_r, first_c), .Cells((first_r + 1) + (first_col * 2) - 4, _
        first_c)), Type:=xlFillDefault 'filling column G
End With

顺便说一下,还有一个提示:how to avoid using select/active statements