简体   繁体   English

VBA检查最后一个单元格是否等于不同工作表上的单元格

[英]VBA to check if last cell equals cell on different sheet

I have a spreadsheet that is used to log information. 我有一个用于记录信息的电子表格。 In one sheet you enter the data then VBA updates a second sheet where the info is stored. 在一张工作表中,输入数据,然后VBA更新第二张工作表,以存储信息。

I want to write a code that will check if a cell on the last row of the log (which will be changing as it updates each time) equals a cell on the input page. 我想编写一个代码来检查日志最后一行中的单元格(每次更新时都会更改)是否等于输入页面上的单元格。

The aim is to stop someone updating the log twice, I already have an alert that it has been updated but want to put a foolproof system in place to stop an entry being logged twice. 目的是阻止某人两次更新日志,我已经有一个警报,说它已被更新,但是想安装一个万无一失的系统来阻止两次记录一个条目。

I am new to VBA so do not really know where to start. 我是VBA的新手,所以真的不知道从哪里开始。

The below is an example of achieving this. 以下是实现此目的的示例。 I have added comments to explain what is happening in the VBA. 我添加了注释以解释VBA中发生的情况。

  1. In Excel, press Alt+F11 在Excel中,按Alt + F11
  2. In the project window on the left, expand it if its not already and double click on 'ThisWorkbook' 在左侧的项目窗口中,将其展开(如果尚未展开),然后双击“ ThisWorkbook”
  3. If it is not already there, type Option Explicit as the first thing in the main window. 如果尚不存在,请在主窗口中首先输入Option Explicit This means the code will not run unless all variables that are used are declared, this is good practice 这意味着除非声明所有使用的变量,否则代码将不会运行,这是一个好习惯
  4. Past the below code into the window 将以下代码粘贴到窗口中
  5. With the cursor in the code you can press F8 to run it line by line to see what is happening or F5 to run it in one go. 将光标置于代码中,您可以按F8一行一行地运行以查看发生了什么,或者按F5一次运行它。

You will want to adjust it to your required workbooks, worksheets, and cells/columns. 您将需要将其调整为所需的工作簿,工作表和单元格/列。

Public Sub Sample()
'Clearly declare variables, in the case we are using them
'to reference a workbook and a worksheet
Dim WkBk    As Workbook
Dim WkSht   As Worksheet

'Set the WkBk variable (which was declared as a workbook,
'which means it can only be used for workbook objects.
'I this instance we are refering to ThisWorkbook,
'which is as it sounds.
Set WkBk = ThisWorkbook

    'We can now make a reference to a specific worksheet
    'within our referenced workbook
    Set WkSht = WkBk.Worksheets("Sheet2")

        'This IF statement is comparing the value of cell
        'A1 on Sheet1 to the the value of the last populated cell
        'in column A of Sheet2 (the sheet we created a reference to)
        If WkBk.Worksheets("Sheet1").Range("A1") = WkSht.Range("A" & WkSht.Rows.Count).End(xlUp) Then
            MsgBox "It was a match"
        End If
    Set WkSht = Nothing
Set WkBk = Nothing

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM