代码要求
在选中的区域中,您可以鼠标选中包含站点名称、经度和纬度信息的行,但请注意,这些行可能包含已经隐藏的单元格。请忽略隐藏单元格中的内容,仅关注每行数据的最后可见信息。您可以利用这些信息建立kml文件,并在生成后自动打开。请注意,选中的区域不包括标题行。
可实现的代码
Sub CreateKMLFile()
Dim fs As Object
Dim f As Object
Dim rng As Range
Dim cell As Range
Dim filename As String
Dim kml As String
' 获取选定区域
Set rng = Selection
' 创建KML文件内容
kml = "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCrLf & _
"<kml xmlns=""http://www.opengis.net/kml/2.2"">" & vbCrLf & _
"<Document>" & vbCrLf
For Each cell In rng.Rows
Dim name As String
Dim longitude As String
Dim latitude As String
name = ""
longitude = ""
latitude = ""
For i = 1 To cell.Columns.Count
If Not cell.Cells(1, i).EntireColumn.Hidden Then
If name = "" Then
name = cell.Cells(1, i).Value
ElseIf longitude = "" Then
longitude = cell.Cells(1, i).Value
ElseIf latitude = "" Then
latitude = cell.Cells(1, i).Value
End If
End If
Next i
If name <> "" And longitude <> "" And latitude <> "" Then
kml = kml & "<Placemark>" & vbCrLf & _
"<name>" & name & "</name>" & vbCrLf & _
"<Point>" & vbCrLf & _
"<coordinates>" & longitude & "," & _
latitude & ",0</coordinates>" & vbCrLf & _
"</Point>" & vbCrLf & _
"</Placemark>" & vbCrLf
End If
Next cell
kml = kml & "</Document>" & vbCrLf & "</kml>"
' 保存KML文件
Set fs = CreateObject("Scripting.FileSystemObject")
filename = Environ("USERPROFILE") & "\Desktop\points.kml"
Set f = fs.CreateTextFile(filename, True, True) ' 修改为UTF-8编码
f.Write kml
f.Close
' 打开KML文件
Shell "explorer.exe """ & filename & """", vbNormalFocus
End Sub