1

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

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

它正在进行中,但想法会有所帮助

4

2 回答 2

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
于 2013-08-17T17:21:26.207 回答
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 引用其他工作簿的优秀提示,包括检查给定文件夹中每个工作簿的方法。

于 2013-08-16T16:01:00.677 回答