比较一个或多个工作簿中的值

我正在尝试编写一个macros,开始执行以下操作:

1电子表格打开时在后台运行。
2比较input的值,即其他工作簿中的名称(如果不存在),请突出显示该事实 – 理想情况下会提供将其添加到工作簿的选项。

总体目标是编写一个资源configuration文件工具,在资源分配过度时“标记”资源,但是帮助上述工作将是一个很好的开始。

到目前为止,我已经设法比较了值,但不能确定我已经查看了所有的工作表

Sub checkname() Dim rCell As Range, vVal1, vVal2 Dim wbCheck As Workbook For Each rCell In Workbooks("Book2.xlt").Worksheets(1).Range("A1:A5") vVal1 = rCell vVal2 = ThisWorkbook.Worksheets(1).Range(rCell.Address) If vVal1 = vVal2 Then MsgBox "valid" MsgBox Worksheets.Count Debug.Print "The value of variable X is: " & vVal1 Debug.Print " vVal1" & vVal2 End If Next rCell End Sub 

它是一项正在进行的工作,但想法会有所帮助

这可以通过Excel公式完成,但是如果您想要检查其他工作簿的每个工作表中的每个单元格,则可能需要在VBA中执行某些操作。 这里是一个例子:

 Dim i as integer, k as integer, j as integer 'We declare our variables. Dim b as Workbook, temp as Worksheet set b = Workbooks("Book2.xlt") 'We set our workbook variable (makes things easier) Dim mySheet As Worksheet Set mySheet = Excel.ActiveSheet 'We set our variable for the current worksheet (the one that contains the original cell). dim myCell as range set myCell = mySheet.Range(rCell.Address) 'We set our original cell variable. This is the cell that has the value we want to check for. 'I used the cell you specified so this will not work if there is an error there. for i = 1 to b.Worksheets.Count 'Loop through each worksheet in the workbook we specified. The worksheet are on a 1-based array so we start with 1 and end at the count. set temp = b.Worksheets(i) 'Set the worksheet variable to make things easier. for k = 1 to temp.UsedRange.Columns.Count 'Loop through each column in the current worksheet's used range. for j = 1 to temp.UsedRange.Rows.Count 'Loop through each row in that column. if temp.Cells(j,k).value = myCell.Value then 'Check the cell for that row+column address for a match. MsgBox "valid" 'If it matches, do something here. MsgBox Worksheets.Count 'Counts the sheets in the current book? Don't know why though. else 'If it doesn't match, do something else here. end if next j 'Complete the loops. next k next i 

一些很棒的VBA参考初学者

这篇文章对VBA有一些很好的说明,可能会为你提供一些帮助。

  • Excelmacros – 只能从一个表单移动到非空单元格

本页面提供了一些关于如何使用VBA引用其他工作簿的精彩提示,包括在给定文件夹中检查每个工作簿的方法。

  • 使用VBA引用Excel工作簿和工作表的10种方法

为了循环工作簿中的工作表,工作表是一个集合,我使用这种结构。

函数IsFileOpen只是在将文件设置为对象variableswb之前检查文件是否需要打开。

 Sub LoopThroughSheets() Dim wb As Excel.Workbook Dim ws As Excel.Worksheet If Not IsFileOpen("myOpenExampleBook.xlsx") Then Excel.Workbooks.Open "pathwayToFile" End If Set wb = Excel.Workbooks("myOpenExampleBook.xlsx") For Each ws In wb.Worksheets Debug.Print ws.Name Next ws End Sub Public Function IsFileOpen(strFile As String) As Boolean Dim aName As String On Error GoTo NotOpen: aName = Workbooks(strFile).Name IsFileOpen = True GoTo FunctionEnd: NotOpen: IsFileOpen = False FunctionEnd: End Function 'IsFileOpen