我在Excel中使用VBA非常新。我想完成的是這個。當用戶輸入5的長度時,則必須將5列顯示爲紅色。然後,當用戶輸入6的寬度時,則必須將6行勾勒爲紅色。例如:根據用戶提供的寬度和高度繪製表格
我迄今這段代碼:
表上的變化:
Private Sub Worksheet_Change(ByVal Target As Range)
If (Target.Address = "$A$2") Then
Call Draw2DTankl
ElseIf (Target.Address = "$B$2") Then
Call Draw2DTankw
End If
End Sub
Draw2DTankl:
Sub Draw2DTankl()
On Error Resume Next
Cells(2, 4).Value = ""
Dim x As Range
Set x = Worksheets("Sheet1").Cells
x.Borders.LineStyle = xNone
Range("A1") = "Length"
Dim Length As Integer
Length = CInt(Cells(2, 1).Value)
If (Length > 30) Then
MsgBox "A length of a maximum 30 is allowed"
Exit Sub
End If
If (Length < 0) Then
MsgBox "Invalid length value entered"
Exit Sub
End If
Dim Rws As Long, Rng As Range, r As Range
If (Length > 0) Then
Rws = 20
Set Rng = Range(Cells(20, "H"), Cells(Rws, 8 + Length - 1))
For Each r In Rng.Cells
With r.Borders
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 3
End With
Next r
End If
If (Err.Number <> 0) Then
MsgBox Err.Description
End If
End Sub
Draw2DTankw:
Sub Draw2DTankw()
On Error Resume Next
Cells(2, 4).Value = ""
Dim x As Range
Set x = Worksheets("Sheet1").Cells
x.Borders.LineStyle = xNone
Range("B1") = "Width"
Dim Width As Integer
Width = CInt(Cells(2, 2).Value)
If (Width > 30) Then
MsgBox "A width of a maximum 30 is allowed"
Exit Sub
End If
If (Width < 0) Then
MsgBox "Invalid Width value entered"
Exit Sub
End If
Dim Col As Long, Rng As Range, r As Range
If (Width > 0) Then
Col = 21
Set Rng = Range(Cells(21, "H"), Cells(Col, 8 + Length - 1))
For Each r In Rng.Cells
With r.Borders
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 3
End With
Next r
End If
If (Err.Number <> 0) Then
MsgBox Err.Description
End If
End Sub
請幫助我。我的代碼不起作用。長度有效,但是當我改變寬度時會剎車。
進入我的長平:
這是正確的。不過,如果我進入6寬度發生這種情況:(我的長短也自敗)
我爲此很長的帖子道歉!
繪製長度後,當您調用子繪圖的寬度時,您正在擦除和重新繪製。由於長度在你的寬度繪製子中被明確指定爲2,所以你將繪製你的坦克2個單位長。如果任何一個單元格被更改,你應該將這些子集合成一個繪製長度和寬度的子集,如Jonathan的答案如下。此外,在格式和結構化問題上做得很好。您顯然已經付出了一些努力來開發您的解決方案。 – asp8811
我明白你的意思了!謝謝!我一定會考慮這一點。此外,謝謝你對帖子的讚揚。 – naheiwProg