vba - xlDown 未按预期工作

标签 vba excel

我关注了this教程

为了处理按钮操作。我想每次在单击按钮时将数据写入新行,但是该代码要么覆盖现有数据,要么将数据写入新行(并再次覆盖它)。

代码:

Private Sub cmdUnesiUBazu_click()
     Sheet1.Activate

    Range("B2").End(xlDown).Offset(1, 0).Select ' want to start write from C2 cell
    ActiveCell.Value = ActiveCell.Offset(-1, 0).Value + 1

    ActiveCell.Offset(0, 1).Value = txtSifraOsobe.Value
    ActiveCell.Offset(0, 2).Value = txtImeIPrezime.Value
    ActiveCell.Offset(0, 3).Value = txtAdresa.Value
    ActiveCell.Offset(0, 4).Value = cboGrad.Value
    ActiveCell.Offset(0, 5).Value = cboDrzava.Value
    ActiveCell.Offset(0, 7).Value = txtDatumRodjenja.Value

  End Sub

最佳答案

最好直接引用单元格,而不是选择它们并引用ActiveCell。观看Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)

您似乎正在尝试创建唯一标识符 (ID) 来引用您的记录。但是您要向下面的空单元格添加 1: ActiveCell.Value = ActiveCell.Offset(1, 0).Value + 1 而不是应该将上面单元格的值加 1 ActiveCell.Value = ActiveCell.Offset(-1, 0).Value + 1

Sheet1.Activate

With Range("B2").End(xlDown).Offset(1, 0)
    .Value = .Offset(-1, 0).Value + 1
    .Offset(0, 1).Value = txtSifraOsobe.Value
    .Offset(0, 2).Value = txtImeIPrezime.Value
    .Offset(0, 3).Value = txtAdresa.Value
    .Offset(0, 4).Value = cboGrad.Value
    .Offset(0, 5).Value = cboDrzava.Value
    .Offset(0, 7).Value = txtDatumRodjenja.Value
End With

关于vba - xlDown 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077505/

相关文章:

excel - 为什么在用户表单中的字段之间切换时 Tab 键有时不起作用?

excel - 有没有办法对单元格地址进行排序?

excel - 尝试使用 Windows API 从电子表格中打开音频文件

Excel VBA : "For" and "If" statement on a single line?

excel - 如何检查关键字列表是否作为子字符串存在于单元格中?并报告匹配的子字符串

vba - 将 Excel 文件保存为不带引号的 .txt 格式

excel - 将数据从 Sheet1 复制到 Sheet2,当列中的值更改时插入行

python - 如何在 Python 的 CSV 文件中查找特定项目的行号?

Excel 消息框选项。单元格包含公式,因此消息框未显示结果

c# - 如何使用 C# 向 Excel 单元格添加超链接