excel 导致编译错误的错误代码问题

2skhul33  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(132)

我目前正试图格式化一个代码块,有人给我在评论上一个问题,但一直得到了很多编译错误。
这个问题的答案是昨天发布的,由于某种原因关闭。它的标题是:Visual basic macro for excel that inserts rows based on quantity of product column [关闭]
代码:

Sub ExpandRows()

Dim lastRow As Long
Dim i As Long
Dim qty As Long
Dim productType As String
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'Insert here your worksheet name
' Assuming data starts from row 2
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
' Loop through each row
For i = lastRow To 2 Step -1
qty = ws.Cells(i, 1).Value
productType = ws.Cells(i, 2).Value
' Insert rows and fill with product type
If qty > 1 Then Rows(i + 1 & ":" & i + qty - 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range(Cells(i, 2), Cells(i + qty - 1, 2)).Value = productType
End If
Next i

End Sub

字符串
我不知道在哪里插入换行符在这结束。代码应该插入行下的产品有一个数量超过一个然后复制下来的产品的描述,以填补插入行的列。
感谢您的任何帮助!
我尝试过用多种方法在底部向上打破行,只是导致越来越多的编译错误,而且我对XML格式不是很熟悉。

vfhzx4xs

vfhzx4xs1#

  • 使用数组转换数据效率更高。
Option Explicit

Sub Demo()
    Dim i As Long, j As Long, k As Long
    Dim arrData, rngData As Range, arrRes
    arrData = ActiveSheet.Range("A1").CurrentRegion.Value
    ReDim arrRes(1 To Application.Sum(Range("a:a")), 1 To UBound(arrData, 2))
    k = 1
    For i = LBound(arrData) + 1 To UBound(arrData)
        For j = 1 To arrData(i, 1)
            If j = 1 Then arrRes(k, 1) = arrData(i, 1)
            arrRes(k, 2) = arrData(i, 2)
            k = k + 1
        Next j
    Next i
    Range("A2").Resize(k - 1, 2).Value = arrRes
End Sub

字符串


的数据

  • Microsoft文档:*

Range.CurrentRegion property (Excel)
Range.Resize property (Excel)
顺便说一句,你的代码应该修改如下。

If qty > 1 Then
            Rows(i + 1 & ":" & i + qty - 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            Range(Cells(i, 2), Cells(i + qty - 1, 2)).Value = productType
        End If

相关问题