上周老師布置了一個作業,内容大緻如下: 給出中國各省份的地圖(為.shp格式),在ArcGIS中用VBA随機生成一個省份,猜此省名并确認。
用ArcGIS 9.2 加載圖層,打開VBA,使用一個textbox 和三個CommandButton ,把三個commandbutton分别命名為“開始”、“确認”、“資訊”,分别用于“随機生成省”、“确認省名”、“猜中的資訊”。
以下是代碼:
Public pav As IActiveView
Dim p1 As Integer
Dim p2 As Integer
Private Sub CommandButton1_Click()
'用于随機生成一個省
Dim pDoc As IMxDocument
Set pDoc = ThisDocument
Dim pMap As IMap
Set pMap = pDoc.FocusMap
Dim i As Integer
i = Int((33 - 0 + 1) * Rnd + 0)
Dim pFeatLyr As IFeatureLayer
Set pFeatLyr = pMap.Layer(0)
Dim pFeatLyrDef As IFeatureLayerDefinition
Set pFeatLyrDef = pFeatLyr
pFeatLyrDef.DefinitionExpression = "FID = " & i
pDoc.ActiveView.Refresh
End Sub
Private Sub CommandButton2_Click()
"在textbox中輸入省名,進行确認工作
Dim sText, sAn As String
sText = TextBox1.Text
Dim pDoc As IMxDocument
Set pDoc = ThisDocument
Dim pMap As IMap
Set pMap = pDoc.FocusMap
Dim pFeatureLyr As IFeatureLayer
Set pFeatureLyr = pMap.Layer(0)
Dim pFeatCursor As IFeatureCursor
Dim pFeat As IFeature
Set pFeat = pFeatCursor
Dim Index As Integer
Index = pFeatureLyr.FeatureClass.Fields.FindField("NAME")
Dim pTable As ITable
Set pTable = pFeatureLyr
Dim pCursor As ICursor
Set pCursor = pTable.Search(Nothing, False)
Dim pRow As IRow
Set pRow = pCursor.NextRow
If sText <> pRow.Value(Index) Then
sAn = pRow.Value(Index)
MsgBox "wrong! 應該是" & sAn
p2 = p2 + 1
Call CommandButton1_Click
Else: MsgBox "right!"
p1 = p1 + 1
p2 = p2 + 1
Call CommandButton1_Click
End If
End Sub
Private Sub CommandButton3_Click()
"進行統計工作
Dim pDoc As IMxDocument
Set pDoc = ThisDocument
Dim pMap As IMap
Set pMap = pDoc.FocusMap
Dim pFeatureLyr As IFeatureLayer
Set pFeatureLyr = pMap.Layer(0)
Dim pFeatCursor As IFeatureCursor
Dim pFeat As IFeature
Set pFeat = pFeatCursor
Dim Index As Integer
Index = pFeatureLyr.FeatureClass.Fields.FindField("NAME")
Dim pTable As ITable
Set pTable = pFeatureLyr
Dim pCursor As ICursor
Set pCursor = pTable.Search(Nothing, False)
Dim pRow As IRow
Set pRow = pCursor.NextRow
If sText = pRow.Value(Index) Then
MsgBox "答對了" & p1 & "題.總共作答" & p2 & "題"
Else
MsgBox "答對了" & p1 & "題.總共作答" & p2 & "題"
End If
End Sub
結尾:這個程式很草率,用人工輸入省名很麻煩,但技術有限不清楚怎樣用一個控件把所有的省份列出進行選擇.