VBA ComboBox复制偶尔失败

时间:2019-03-12 16:07:03

标签: excel vba combobox activex

我正在创建一个带有3个组合框的表单,用户可以填写。当他们单击“新建行”按钮时,表单应在带有3个空白组合框的最新行的正下方创建一个新行。

问题:有时,当用户不按顺序选择其中一个框时(例如,他们在combobox1之前单击了combobox 2),然后单击“新行”按钮,后两个框正确复制,但第一个组合框未复制到正确的行。它总是复制到表格的左上角。 (查看视觉效果)

正确:

Correct result

不正确:

Incorrect result

这是我的代码:

'Declare variables
Dim curIndirectRow As Integer

'Search for keyword in column B; search direction: top to bottom
'Set findTable to the coordinates of matching word
Set findTable = ThisWorkbook.Sheets("Main").Range("B:B").Find(What:="Indirect Damages", LookIn:=xlValues, LookAt:=xlWhole, searchdirection:=xlNext)

'If the line immediately after the found word is blank (meaning it's the first row)
If Range(findTable.Address).Offset(1, 0) = "" Then
    'set variable to be the first row
    curIndirectRow = Range(findTable.Address).Row
    Else
    'set variable to be the last row in the table
    curIndirectRow = ThisWorkbook.Sheets("Main").Range(findTable.Address).End(xlDown).Row
End If

'Add one blank row underneath your last row
Range("$B$" & curIndirectRow).Offset(1).EntireRow.Insert Shift:=xlShiftDown
'Copy the row above it into your newly inserted row(no buttons included)
Sheets("Main").Range("B" & CStr(findTable.Row) & ":F" & CStr(findTable.Row)).Copy Destination:=Sheets("Main").Range("B" & CStr(curIndirectRow + 1) & ":F" & CStr(curIndirectRow + 1))
'Clear the values of the Approver cell
Sheets("Main").Range("$F$" & CStr(curIndirectRow + 1)).Value = ""

'Select the first box ("Type") and copy
Sheets("Main").Shapes.Range(Array("Combobox8")).Select
Selection.Copy
'Paste the first box into your new row's C column
Sheets("Main").Range("C" & CStr(curIndirectRow + 1)).PasteSpecial
'Populate the drop down list
Sheets("Main").Shapes("ComboBox" & CStr(Sheets("Main").Shapes.Count - 63)).OLEFormat.Object.ListFillRange = "=Lists!D2:D6"
'Set the default value to blank
Sheets("Main").OLEObjects("ComboBox" & CStr(Sheets("Main").Shapes.Count - 63)).Object.Value = ""

第二个和第三个框重复第一个框的代码。请注意,我从工作表上的“形状”计数中减去63,因为还有其他63个非组合框形状(复选框等)。

0 个答案:

没有答案