Discussion:
請問 VBA 如何以 for 迴圈檢查一列連續的欄位值? (包含資料與程式)
(时间太久无法回复)
annie
2005-04-16 19:29:26 UTC
Permalink
我有兩行省略過後的欄位值如下(A1:B9)
北區 北區 中區 中區 南區 南區 北區 中區 南區
49.20 1667.75 4950.00 280.00 866.40 2100.00 2225.95 600.00 750.00

希望能檢查(A1:A9)欄位值是北區、中區或南區中的哪一個區域
目標是想找出屬於同一個區域的欄位(ex.A1,A2),並將相對應的數值欄位做相加(ex.B1+B2)存在一個新的欄位(ex.C1)

我嘗試過下面的寫法,但執行後出現: 執行階段錯誤'1004',應用程式或物件定義上的錯誤
不好意思,這是我第一次自己寫,如果錯的很笨請多見諒並麻煩各位前輩告訴我該如何修改,謝謝!

Sub 區分區域()
Dim x As Integer
Dim y As Integer
Dim sum1 As Integer
Dim sum2 As Integer
Dim sum3 As Integer
Dim sum4 As Integer

With Sheet1.Cells(x, y)
For x = 2 To 32
If Cells(x, 1) = "北區" Then
sum1 = sum1 + Cells(x, 2)
ElseIf Cells(x, 1) = "中區" Then
sum2 = sum1 + Cells(x, 2)
Else
sum3 = sum1 + Cells(x, 2)
End If
Next
End With
unknown
2005-04-18 03:13:02 UTC
Permalink
你的程式中有3個問題:
1. x, y必須assign初始值,否則在呼叫Cells(x, y)時無法指定物件
2.
VBA使用活頁簿物件的語法是Worksheets(index),所以你想要指定Worksheets物件,語法為Worksheets(1).Cells(x,y)或Worksheets("Sheet1").Cells(x,y)
3. Cells(x, y)的x是Row列,y是column欄,如果依你的欄位來看,應該把Cells(x, 1)改為用Cells(1, y)來用廻圈尋找
程式修改如下:

Sub 區分區域()
Dim x As Integer
Dim y As Integer
Dim sum1 As Integer
Dim sum2 As Integer
Dim sum3 As Integer
Dim sum4 As Integer

x=1
y=1

With WorkSheets("Sheet1").Cells(x, y)
For y = 2 To 32
If Cells(1, y) = "北區" Then
sum1 = sum1 + Cells(2, y)
ElseIf Cells(1, y) = "中區" Then
sum2 = sum1 + Cells(2, y)
Else
sum3 = sum1 + Cells(2, y)
End If
Next
End With
unknown
2005-04-18 03:29:01 UTC
Permalink
Sorry…你Cells的欄列沒有問題,是我看漏了你在前面的說明。
所以主要是活頁簿物件使用法和初始值的問題。

"神氣豬" 來函:
Post by unknown
你的程式中有3個問題:
1. x, y必須assign初始值,否則在呼叫Cells(x, y)時無法指定物件
2.
VBA使用活頁簿物件的語法是Worksheets(index),所以你想要指定Worksheets物件,語法為Worksheets(1).Cells(x,y)或Worksheets("Sheet1").Cells(x,y)
3. Cells(x, y)的x是Row列,y是column欄,如果依你的欄位來看,應該把Cells(x, 1)改為用Cells(1, y)來用廻圈尋找
程式修改如下:
Sub 區分區域()
Dim x As Integer
Dim y As Integer
Dim sum1 As Integer
Dim sum2 As Integer
Dim sum3 As Integer
Dim sum4 As Integer
x=1
y=1
With WorkSheets("Sheet1").Cells(x, y)
For y = 2 To 32
If Cells(1, y) = "北區" Then
sum1 = sum1 + Cells(2, y)
ElseIf Cells(1, y) = "中區" Then
sum2 = sum1 + Cells(2, y)
Else
sum3 = sum1 + Cells(2, y)
End If
Next
End With
Loading...