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

时间:2013-08-16 15:51:22

标签: excel excel-vba vba

我正在尝试编写一个宏,它将通过执行以下操作开始:

1打开电子表格时在后台运行 2比较输入的值,即另一个工作簿中的名称,如果它不存在,则突出显示该事实 - 理想情况下,可以选择将其添加到工作簿中。

总体目标是编写一个资源配置文件工具,当资源过度分配时会“标记” - 但对上述内容的帮助将是一个很好的开始。

到目前为止,我已设法比较值,但无法确定我已查看所有工作表

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

这项工作正在进行中,但想法会有所帮助

2 个答案:

答案 0 :(得分:0)

很多可以在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有一些很好的说明,可以为你提供更多的帮助。

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

答案 1 :(得分:0)

要遍历工作簿中的工作表,因为工作表是一个集合,我使用这种结构。

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

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