用于在Excel模板中插入行的功能,其中包含来自列表框的数据无法正常运行

时间:2019-02-24 19:40:50

标签: excel vba excel-formula

当在Excel工作表中插入列表数据时,我的列表框项目包含更多项目/行时,我遇到了问题。位置1的第一组数据始终可以很好地工作,并以应有的方式插入所有内容,但是如果我对功能的理解不够,有时位置2将可以工作。在第二个位置之后,我什么也无法正确插入值,并且总是弄乱并将行插入错误的位置,或者弄乱了位置部分末尾的求和公式。

是否可以使用随机的listcount变量插入行?我目前设置的方式是,如果列表框中有15个以上的项目,则需要在listcount之后插入x号,然后对其余位置在每个位置执行相同的操作。

Private Sub testbtn_Click()
Dim excelApp As Excel.Application
Dim targetWB As Workbook
Dim targetRange As Range
Set excelApp = New Excel.Application
Dim fName As String
Dim xcelObj As Object
Set xcelObj = CreateObject("Scripting.FileSystemObject")

fName = ("Test - " & Format(Date, "mm-dd-yyyy"))

If FileExists(ThisWorkbook.Path & "\" & "template.xlsm") = False Then Exit Sub

If FileExists(ThisWorkbook.Path & "\" & fName & ".xlsm") = False Then
xcelObj.CopyFile ThisWorkbook.Path & "\template.xlsm", ThisWorkbook.Path & "\" & fName & ".xlsm"
End If

Set targetWB = excelApp.Workbooks.Open(ThisWorkbook.Path & "\" & fName & ".xlsm")

Dim n As Integer
L = lb1.List
n = (UBound(L) + 1) - 15


Call Sheet_AddLBRangeTest(targetWB, 1, 30, dtp.lb1, dtp.lb2, "A16", "B16")

Call Sheet_AddLBRangeTest(targetWB, 1, 51 + n, dtp.lb1, dtp.lb2, "A" & 37 + n, "B" & 37 + n)

Call Sheet_AddLBRangeTest(targetWB, 1, 72 + n + 7, dtp.lb1, dtp.lb2, "A" & 58 + n + 7, "B" & 58 + n + 7)

Call Sheet_AddLBRangeTest(targetWB, 1, 93 + n + 14, dtp.lb1, dtp.lb2, "A" & 79 + n + 14, "B" & 79 + n + 14)

Call Sheet_AddLBRangeTest(targetWB, 1, 114 + n + 21, dtp.lb1, dtp.lb2, "A" & 100 + n + 21, "B" & 100 + n + 21)

'Call Sheet_AddLBRange(targetWB, 1, dtp.lb1, dtp.lb2, "D16", "F16")



targetWB.Close (True)
excelApp.Quit

End Sub

'这是来自我的模块 '检查文件是否存在的功能

Function FileExists(sFullPath As String) As Boolean
    Dim fOBJ As Object
    Set fOBJ = CreateObject("scripting.filesystemobject")
    FileExists = fOBJ.FileExists(sFullPath)
End Function

'函数,用于将列表框添加到Excel工作表中

Public Sub Sheet_AddLBRangeTest(Wb As Workbook, SN As Integer, RN As Integer, lb1 As MSForms.listbox, lb2 As MSForms.listbox, Cell1 As String, Cell2 As String)
    Dim L As Variant
    Dim L2 As Variant
    Dim n As Integer
    L = lb1.List
    L2 = lb2.List

        If lb1.ListCount = 0 Then
                Wb.Sheets(SN).Range(Cell1).Resize(1, 1).Value = 0
        Else
            If UBound(L) + 1 > 15 Then
                n = (UBound(L) + 1) - 15
                Wb.Sheets(SN).Rows(RN).Resize(n).Insert
            End If
                Wb.Sheets(SN).Range(Cell1).Resize(UBound(L) + 1, 1).Value = L
        End If

        If lb2.ListCount = 0 Then
                Wb.Sheets(SN).Range(Cell2).Resize(1, 1).Value = 0
        Else
                Wb.Sheets(SN).Range(Cell2).Resize(UBound(L2) + 1, 1).Value = L2
        End If
    End Sub

This is a screen shot of my template excel file

Messes up here

0 个答案:

没有答案