Excel VBA:使用xlDown和Offset在单元格中插入值

时间:2016-09-24 14:37:40

标签: excel vba excel-vba

我在使用我的代码从InputBox插入值时遇到了一些麻烦。特别是违规行如下:

Set p = nPoints.End(xlDown).Offset(1, 0)
            p.Value = nPointVal

应该做的是找到电子表格的最后一行,右边第一个可用的单元格,然后插入存储的值nPointVal。但是,它不是这样做的,它根本不插入任何东西。非常感谢任何帮助,我的完整代码如下。

Sub takeTwo()

On Error Resume Next

Dim fNameString As Variant
Dim lNameString As Variant
Dim sEmailString As Variant
Dim nPointVal As Integer
Dim sEventName As String
Dim n As Integer, r As Long, c As Range, d As Range, e As Range, p As Range, sE As Range
Dim fName As Range, lName As Range, sEmail As Range, nPoints As Range
Dim lEvent As Integer
Set fName = ActiveSheet.Range("FirstName")
Set lName = ActiveSheet.Range("LastName")
Set sEmail = ActiveSheet.Range("eMailAddr")


fNameString = Split(Application.InputBox("First Names in comma delimited format.", Type:=2), ",")
lNameString = Split(Application.InputBox("Last Names in comma delimited format.", Type:=2), ",")
sEmailString = Split(Application.InputBox("Email Addresses in comma delimited format.", Type:=2), ",")
nPointVal = InputBox("Please enter a point value for this event")
sEventName = InputBox("Please enter the name of the event.")

lEvent = NextEmptyColumn(Range("A1"))
Set sE = Range("A1").Offset(0, lEvent)
sE.Value = sEventName
' sEventPos = sE.Offset(0, lEvent)

If fNameString <> False And lNameString <> False Then

    For i = LBound(fNameString) To UBound(fNameString)

        fNameString(i) = Trim(fNameString(i)) ' Trim off leading and trailing whitespace.
        lNameString(i) = Trim(lNameString(i)) ' Trim off leading and trailing whitespace.

        Set c = fName.Find(fNameString(i), LookIn:=xlValues, LookAt:=xlWhole)
        Set d = lName.Find(lNameString(i), LookIn:=xlValues, LookAt:=xlWhole)

        If c And d Is Nothing Then

            Set c = fName.End(xlDown).Offset(1, 0)
            c.Value = fNameString(i)
            Set d = lName.End(xlDown).Offset(1, 0)
            d.Value = lNameString(i)
            Set e = sEmail.End(xlDown).Offset(1, 0)
            e.Value = sEmailString(i)
            Set p = nPoints.End(xlDown).Offset(1, 0)
            p.Value = nPointVal

            Dim s As Range ' Our summation range
            Set s = Range(c.Offset(0, 5), c.Offset(0, c.EntireRow.Columns.Count - 1))

            ' c.Offset(1, 3).Formula = "=((" & s.Address & ""

        End If

    Next


End If

End Sub

1 个答案:

答案 0 :(得分:0)

所以我找到了一个更简单的解决方案:

Set p = fName.End(xlDown).Offset(0, lEvent)
            p.Value = nPointVal

这引用了插入名称所在的同一行,这是我们想要的,因为点值与此人有关。如果可能存在一些问题,请提供建议。