VBA Excel宏通过外部文件更新列表

VBA Excel宏通过外部文件更新列表,vba,excel,excel-2010,Vba,Excel,Excel 2010,我有一张excel表格,有两张表格。有一张表是隐藏的,它有一个名为“Location”的值列表。在主表上,我创建了一个下拉菜单,从隐藏的表中提取 如何将这些值存储在外部文件(Excel、.txt等)中,以便按下宏按钮(VBA),用存储在外部文件中的任何/所有新位置值替换/更新隐藏工作表上的列表?我相信这就是您要寻找的: Dim intPointer as Integer Dim strFileToImport as String Dim strLine as String intPointer

我有一张excel表格,有两张表格。有一张表是隐藏的,它有一个名为“Location”的值列表。在主表上,我创建了一个下拉菜单,从隐藏的表中提取


如何将这些值存储在外部文件(Excel、.txt等)中,以便按下宏按钮(VBA),用存储在外部文件中的任何/所有新位置值替换/更新隐藏工作表上的列表?

我相信这就是您要寻找的:

Dim intPointer as Integer
Dim strFileToImport as String
Dim strLine as String

intPointer = FreeFile()
Open strFileToImport For Input Access Read Lock Read As #intPointer
Do Until EOF(intPointer)
    Line Input #intPointer, strLine
    SheetWithLocations.Cells(lngRow, 1).Value2 = strLine
    lngRow = lngRow + 1
Loop

它打开一个名为strFileToImport的外部txt文件,逐行读取txt文件并将其写入SheetWithLocations中。

假设包含位置的外部文件的文件路径为: “D:\Location.xls”

Location.xls只有一张名为“sheet1”的图纸,其结构如下:

Locations E:\123.txt C:\MyFolder\MyOtherFile.xls D:\MyFile.xls . . etc.
你写代码了吗?您是否尝试过从外部文件读取数据?将任务拆分为较小的步骤,然后尝试从中进行计算。构建连接到外部工作簿的microsoft查询可能更容易,然后宏所要做的就是刷新查询。需要考虑的问题。请不要忘记添加“microsoft activex数据对象2.1库”作为VB宏编辑器窗口中引用库中的项目引用
Private Sub macroUpdateLocations ()
    Dim myCon As New ADODB.Connection
    Dim myRs As New ADODB.Recordset
    Dim iCounter As Long
    myCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Location.xls;Extended Properties=" & """Excel 8.0;HDR=Yes;IMEX=1;""" & ";"
    Set myRs = myCon.Execute("SELECT * FROM `Sheet1$`")
    Worksheets("sheet2").Range("A:A").ClearContents
    Worksheets("sheet2").Range("A1").Value = "Locations"
    iCounter = 2
    Do While Not myRs.EOF
        Worksheets("sheet2").Range("A" & CStr(iCounter)).Value = myRs(0)
        iCounter = iCounter + 1
        myRs.MoveNext
    Loop
End Sub
myRs.Close
Set myRs = Nothing
myCon.Close
Set myCon = Nothing