我想在我的Excel表格中循環行。該行基於讀入工作表的數據進行移動,並且列是可變的,並根據數據進行更改。所有的按鈕都是由另一個宏生成的,按下後將其內容輸入到我想要讀取的行中。 Excel VBA:基於變量選擇單元格
我的問題是,當我嘗試引用帶有變量的單元格時,無論我嘗試什麼,我都會得到一個錯誤。最常見的錯誤是'類型不匹配'
Sub Save()
Dim RowNum As Integer
Dim LastColumn As Long
Dim ws As Worksheet
Dim MyRange As Range
Dim answer As Integer
Dim i As Integer
Set ws = ActiveWorkbook.Sheets("Main")
answer = MsgBox("Sind Sie sicher, dass Sie speichen möchten?", vbYesNo + vbQuestion, "Sind Sie sicher")
If answer = vbNo Then
Exit Sub
End If
Application.ScreenUpdating = False
'Finds the location of the button ("Speichen Freigegebene Protokolle") is pressed in order to locate the desired row
RowNum = ws.Buttons(Application.Caller).TopLeftCell.row
'Finds how many columns there are with this data set
LastColumn = ws.Cells(11, ws.Columns.count).End(xlToLeft).Column
'cycles through columns of the row
For i = 7 To LastColumn
Set MyRange = ws.Range(Cells(RowNum, i), Cells(RowNum + 1, i))
If MyRange.Value = "Gut" Then '##Type Mismatch error##
'Save
ElseIf MyRange.Value = "Einzelfreigeben" Then
'Save
ElseIf MyRange.Value = "Nacharbeit" Then
'Dont Save
ElseIf MyRange.Value = "Ausschuss" Then
'Dont save
ElseIf MyRange.Value = "" Then
Err = MsgBox("Fehler! Sie haben eine Protokole zu pruefen vergessen.", vbOKOnly, "Fehler")
Exit Sub
End If
Next i
End Sub
任何幫助將非常感激!
您正嘗試從多個單元格中獲取單個值。只選擇具有該值的單元格。你需要改變這一行:Set MyRange = ws.Range(Cells(RowNum,i),Cells(RowNum + 1,i))',因此它只涉及一個單元格。我的猜測是,你要'設置MyRange = ws.Cells(ROWNUM + 1,I)' –
您嘗試將MULT單元格區域的值(這是一個數組)比較單一的價值,你不能用'='來實現。什麼目的?此外,您還需要'ws'來調用'Cells':'Set MyRange = ws.Range(ws.Cells(RowNum,i),ws.Cells(RowNum + 1,i))' – Rory
Thanks @ScottCraner and @羅裏!!!!只引用最上面的單元格已經解決了這個問題。感謝您的幫助,我沒有意識到您只需引用合併單元格的頂部單元格即可獲取其內容。 – sheds141