我对 VBA 相当陌生,我需要制作一个宏来检查数据库中的每一列是否与模板表相对应。我已经让代码工作了,但是当我四处移动以定位要按我想要的方式显示的文本时,我在 If 语句中不断收到错误“需要对象”。任何帮助,将不胜感激。
Sub checkValues()
'Initalizes integers that will be used
Dim rwIndex As Long '"Item Attributes" row index
Dim colIndex As Long '"Item Attributes" column index
Dim rowEnd As Long 'Last row in "Item Attributes"
Dim colEnd As Long 'Last column in "Item Attributes"
Dim tempIndex As Integer 'Index used to move down 'Lookup Code' column in the template table
Dim resRow As Long 'Current row in "Report" to paste
Dim resCol As Long 'Current column in "Report" to paste
'Initializes the worksheets that will be usedd
Dim shnam1 As Worksheet
Dim shnam2 As Worksheet
Dim shnam3 As Worksheet
'Sets the worksheets for the workbook
Set shnam1 = Sheets("Item Attributes")
Set shnam2 = Sheets("Table")
Set shnam3 = Sheets("Report")
'Gets bounds for "Item Attributes" table
rowEnd = shnam1.Cells(Application.Rows.Count, 1).End(xlUp).Row
colEnd = shnam1.Cells(1, Application.Columns.Count).End(xlToLeft).Column
Call clearReport(shnam3) 'Clear results before every use
'Let the user know that the report is being made
Application.ScreenUpdating = False
Application.StatusBar = "Creating the report..."
Application.DisplayAlerts = True
'Report Heading
shnam3.Cells(1, 1).Value = "Oracle Part Number"
shnam3.Cells(1, 2).Value = "Description"
shnam3.Cells(1, 3).Value = "Attribute Name"
shnam3.Cells(1, 4).Value = "Attribute Value"
shnam3.Cells(1, 5).Value = "Correct Value"
resRow = 2 'Set row for Results
'From 2nd row to last row
For rwIndex = 2 To rowEnd
tempIndex = 3 'Template table index
resCol = 1 'Set column for results
'From 3rd column to last column
For colIndex = 3 To colEnd
'Compare selection in data to template table
If (shnam1.Cells(rwIndex, colIndex).Value) <> (shnam2.Cells(tempIndex, 1).Value) Then
'Copy oracle part number and description
shnam1.Range(shnam1.Cells(rwIndex, 1), shnam1.Cells(rwIndex, 2)).Copy shnam3.Cells(resRow, resCol)
'Copy attribute name
shnam2.Cells(tempIndex, 2).Copy shnam3.Cells(resRow, resCol + 2)
'Copy correct attribute value
shnam2.Cells(tempIndex, 1).Copy shnam3.Cells(resRow, resCol + 3)
'Copy incorrect attribute value
shnam1.Cells(rwIndex, colIndex).Copy shnam3.Cells(resRow, resCol + 4)
resRow = resRow + 1 'Move down a row in the "Report" table
End If
tempIndex = tempIndex + 1 'Increment through template table
Next colIndex
Next rwIndex
'Turn on screen updating
Application.ScreenUpdating = True
'Format "Report" table
Call formatReport(shnam3)
'Turn off status bar and display that the report has finished
Application.StatusBar = False
Msgbox "The report has been created."
End Sub
'Clear the "Report" table
Sub clearReport(shnam As Worksheet)
shnam.Select
Cells.Select
Selection.ClearContents
End Sub
'Adjust all text to be orientated on the left in "Report" table
Sub formatReport(shnam As Worksheet)
shnam.Select
Cells.Select
Selection.NumberFormat = "@"
End Sub