回答編集履歴

2

コード修正

2020/12/10 08:42

投稿

hatena19
hatena19

スコア34073

test CHANGED
@@ -24,23 +24,23 @@
24
24
 
25
25
 
26
26
 
27
- Dim r As Range
27
+ Dim i As Long
28
28
 
29
- For Each r In rng.Rows
29
+ For i = rng.Rows.Count To 1 Step -1
30
30
 
31
- If WorksheetFunction.Count(r) = 0 Then
31
+ If WorksheetFunction.Count(rng.Rows(i)) = 0 Then
32
32
 
33
- r.EntireRow.Delete
33
+ rng.Rows(i).EntireRow.Delete
34
34
 
35
35
  End If
36
36
 
37
37
  Next
38
38
 
39
- For Each r In rng.Columns
39
+ For i = rng.Columns.Count To 1 Step -1
40
40
 
41
- If WorksheetFunction.Count(r) = 0 Then
41
+ If WorksheetFunction.Count(rng.Columns(i)) = 0 Then
42
42
 
43
- r.EntireColumn.Delete
43
+ rng.Columns(i).EntireColumn.Delete
44
44
 
45
45
  End If
46
46
 
@@ -68,35 +68,37 @@
68
68
 
69
69
  ```vba
70
70
 
71
- Public Sub DelBlankRowCol2()
71
+ Public Sub DelBlankRowCol()
72
72
 
73
73
 
74
74
 
75
75
  Dim rng As Range
76
76
 
77
- Set rng = Range("A1").CurrentRegion
77
+ With Range("A1").CurrentRegion
78
78
 
79
- Set rng = rng.Offset(1, 1).Resize(rng.Rows.Count - 2, rng.Columns.Count - 2)
79
+ Set rng = .Offset(1, 1).Resize(.Rows.Count - 2, .Columns.Count - 2)
80
+
81
+ End With
80
82
 
81
83
 
82
84
 
83
- Dim r As Range
85
+ Dim i As Long
84
86
 
85
- For Each r In rng.Rows
87
+ For i = rng.Rows.Count To 1 Step -1
86
88
 
87
- If WorksheetFunction.Count(r) = 0 Then
89
+ If WorksheetFunction.Count(rng.Rows(i)) = 0 Then
88
90
 
89
- r.EntireRow.Delete
91
+ rng.Rows(i).EntireRow.Delete
90
92
 
91
93
  End If
92
94
 
93
95
  Next
94
96
 
95
- For Each r In rng.Columns
97
+ For i = rng.Columns.Count To 1 Step -1
96
98
 
97
- If WorksheetFunction.Count(r) = 0 Then
99
+ If WorksheetFunction.Count(rng.Columns(i)) = 0 Then
98
100
 
99
- r.EntireColumn.Delete
101
+ rng.Columns(i).EntireColumn.Delete
100
102
 
101
103
  End If
102
104
 

1

コード追記

2020/12/10 08:42

投稿

hatena19
hatena19

スコア34073

test CHANGED
@@ -53,3 +53,55 @@
53
53
 
54
54
 
55
55
  データが数値だけなの場合はこれでいいですが、文字もあるなら、CountA関数に変更してください。
56
+
57
+
58
+
59
+ 追記
60
+
61
+ ---
62
+
63
+
64
+
65
+ **最終行、最終列にデータがある場合のコードは下記で。**
66
+
67
+
68
+
69
+ ```vba
70
+
71
+ Public Sub DelBlankRowCol2()
72
+
73
+
74
+
75
+ Dim rng As Range
76
+
77
+ Set rng = Range("A1").CurrentRegion
78
+
79
+ Set rng = rng.Offset(1, 1).Resize(rng.Rows.Count - 2, rng.Columns.Count - 2)
80
+
81
+
82
+
83
+ Dim r As Range
84
+
85
+ For Each r In rng.Rows
86
+
87
+ If WorksheetFunction.Count(r) = 0 Then
88
+
89
+ r.EntireRow.Delete
90
+
91
+ End If
92
+
93
+ Next
94
+
95
+ For Each r In rng.Columns
96
+
97
+ If WorksheetFunction.Count(r) = 0 Then
98
+
99
+ r.EntireColumn.Delete
100
+
101
+ End If
102
+
103
+ Next
104
+
105
+ End Sub
106
+
107
+ ```