簡體   English   中英

VBA檢查最后一個單元格是否等於不同工作表上的單元格

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

我有一個用於記錄信息的電子表格。 在一張工作表中,輸入數據,然后VBA更新第二張工作表,以存儲信息。

我想編寫一個代碼來檢查日志最后一行中的單元格(每次更新時都會更改)是否等於輸入頁面上的單元格。

目的是阻止某人兩次更新日志,我已經有一個警報,說它已被更新,但是想安裝一個萬無一失的系統來阻止兩次記錄一個條目。

我是VBA的新手,所以真的不知道從哪里開始。

以下是實現此目的的示例。 我添加了注釋以解釋VBA中發生的情況。

  1. 在Excel中,按Alt + F11
  2. 在左側的項目窗口中,將其展開(如果尚未展開),然后雙擊“ ThisWorkbook”
  3. 如果尚不存在,請在主窗口中首先輸入Option Explicit 這意味着除非聲明所有使用的變量,否則代碼將不會運行,這是一個好習慣
  4. 將以下代碼粘貼到窗口中
  5. 將光標置於代碼中,您可以按F8一行一行地運行以查看發生了什么,或者按F5一次運行它。

您將需要將其調整為所需的工作簿,工作表和單元格/列。

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