English 中文(简体)
a. 提供封闭式工作手册,不开放
原标题:Query a closed workbook without opening it

I m searching for a string within a column of a closed Excel workbook.

The following code gives a type mismatch error on MsgBox.

如果我用<代码>ret = “和amp; wbPath & “[”和amp; wbame & “]”和amp; wsame &“Namp”;“C3015” 地址(True, Real, -4150),然后,宏观面值给我硬编码(在这种情况下,C3015室的价值)。

我如何在封闭式工作手册一栏中寻找其他价值,而不开放这些价值?

 Dim wbName As String, wbPath As String, wsName As String

 wbPath = "PathToWorkbook"
 wbName = "NameOfWorkbook.xlsb"
 wsName = "NameOfWorkSheet"

 Dim ret As String    

 ret = " " & wbPath & "[" & wbName & "]" & wsName & " !" & Range("D:D").Find(What:="SearchColumnDForThisString")

 MsgBox ExecuteExcel4Macro(ret) // <--------- TYPE MISMATCH ERROR
问题回答

如果你在不止一个宏观上使用该书,你可能想离开该书的开放,那么你可以做如下事情来打开和隐藏该书。 你们还可以把工作手册放在一个公开的变量上,以便你能够在你完成的时候结束工作。

Dim Wn as Window
Dim Wb as Workbook

Application.ScreenUpdating = False

Set Wb = Application.Workbooks.Open("your book")

For Each Wn in Wb
    Wn.Visible = False
Next Wn

Application.ScreenUpdating = True

当时还使用on、 s、ado、或另一种语言或微粒,用on或西sim,用直截了当的本地方式盘问封闭式工作手册(在关闭时打上一本工作手册)。 但是,我们认为我们可以开设一个工作手册inviible。 你在(”时暗示,可以开诚布公,但藏匿(或实际上不展示)一本工作书?

Sub FindInClosedWorkbookpartmanyallXLSB()

Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim searchStr As String
Dim foundCell As Range
Dim firstAddress As String
Dim addresses As String

  Set the string you are searching for
searchStr = "S"

Application.ScreenUpdating = False
Application.DisplayAlerts = False

  Open the workbook invisibly
Set wb = Workbooks.Open("C:UserskarmaDocumentsworkbook test to search.xlsb", ReadOnly:=True, UpdateLinks:=False)
wb.Windows(1).Visible = False

  Set the worksheet you want to search in
Set ws = wb.Worksheets("Sheet1")

  Search in column G   i know you asked for D:D
Set rng = ws.Range("G:G")

  Use the Find method to search for the string
Set foundCell = rng.Find(What:=searchStr, LookIn:=xlValues, LookAt:=xlPart)

If Not foundCell Is Nothing Then
      Save the address of the first found cell
    firstAddress = foundCell.Address

    Do
          Add the address to the addresses string
        addresses = addresses & foundCell.Address & vbCrLf

          Continue searching
        Set foundCell = rng.FindNext(after:=foundCell)
        
      Loop while we have not returned to the first found cell
    Loop While Not foundCell Is Nothing And foundCell.Address <> firstAddress

      Display a single message box with all addresses
    MsgBox "Found " & searchStr & " at: " & vbCrLf & addresses

Else
    MsgBox searchStr & " not found."
End If

  Close the workbook you were searching without saving
wb.Close SaveChanges:=False

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

我的榜样是用Xlpart在G栏中搜索任何座标,S 。 但是,如果你想要的话,你可以回头看血管和单一结果(通过拆除 lo)。

如果你想要在宏观运行的手册表1中取得结果,你可以这样做:

Dim wb thisWb As Workbook
Dim ws thisWs As Worksheet

页: 1

Set the workbook and worksheet where the macro resides
Set thisWb = ThisWorkbook
Set thisWs = thisWb.Sheets("Sheet1")

页: 1

    Loop while we have not returned to the first found cell
    Loop While Not foundCell Is Nothing And foundCell.Address <> firstAddress

Else
    thisWs.Cells(rowNumber, "I").Value = searchStr & " not found."
End If

  Close the workbook you were searching without saving
wb.Close SaveChanges:=False

-------- 2 with python though it can be done alot easier:

<> 全文> 计算机:

## 
import pandas as pd
from pyxlsb import open_workbook as open_xlsb

# Set the string you are searching for
searchStr =  S 

df = []

with open_xlsb(r C:UserskarmaDocumentsworkbook test to search.xlsb ) as wb:
with wb.get_sheet(1) as sheet:  # Sheet index start at 1
    for row in sheet.rows():
        df.append([item.v for item in row])  # .v to fetch the value of the cell

df = pd.DataFrame(df[1:], columns=df[0])  # df[0] contains column names

results = df.isin([searchStr])

if results.any().any():   # .any().any() checks if there s any True in the entire DataFrame
print(f Found "{searchStr}" at: )
series = results.unstack()  # this converts the DataFrame to a multi-index Series
for idx, value in series.items():
    if value:
        print(f Row {idx[1]}, Column {idx[0]} )  # idx is a tuple with (column, row)
 else:
 print(f "{searchStr}" not found. )

For partial matches anywhere in thw sheet workbook or part of a cell:

import pandas as pd
from pyxlsb import open_workbook as open_xlsb

# Set the string you are searching for
searchStr =  S 

df = []

with open_xlsb(r C:UserskarmaDocumentsworkbook test to search.xlsb ) as wb:
with wb.get_sheet(1) as sheet:  # Sheet index start at 1
    for row in sheet.rows():
        df.append([item.v for item in row])  # .v to fetch the value of the cell

df = pd.DataFrame(df[1:], columns=df[0])  # df[0] contains column names

mask = df.applymap(lambda x: searchStr in str(x))  # applymap works element-wise on a DataFrame

if mask.any().any():   # .any().any() checks if there s any True in the entire DataFrame
print(f Found "{searchStr}" at: )
series = mask.unstack()  # this converts the DataFrame to a multi-index Series
for idx, value in series.items():
    if value:
        print(f Row {idx[1]}, Column {idx[0]} )  # idx is a tuple with (column, row)
else:
 print(f "{searchStr}" not found. )

你们可以看到,你要求解决的问题可以解决,而且只能靠本土做,似乎无情地用沙捞。 它是本土的。

but with and for VBA , best we could do is mimick not opening the file , and doing so "invisibly" in combo with what Tim Williams said .

Something cool from/using cmd (To look really cool you could query from CMD you could save a script like this and do all the calling from cmd).

import pandas as pd
from pyxlsb import open_workbook as open_xlsb
import argparse

# Create the parser and add arguments
parser = argparse.ArgumentParser()
parser.add_argument("--search", help="The string to search for", required=True)
parser.add_argument("--file", help="The path to the .xlsb file", required=True)
args = parser.parse_args()

# Extract arguments
searchStr = args.search
filePath = args.file

# Open the xlsb file
with open_xlsb(filePath) as wb:
for sheet_name in wb.sheets:  # iterate through each sheet
    df = []

    # Read the sheet into a DataFrame
    with wb.get_sheet(sheet_name) as sheet:
        for row in sheet.rows():
            df.append([item.v for item in row])

    df = pd.DataFrame(df[1:], columns=df[0])

    # Iterate over each column
    for column_name in df.columns:
        # Convert the column to string type and check if it contains the search string
        # Fill NA/NaN values with an empty string before converting to string
        column_as_str = df[column_name].fillna(  ).astype(str)

        # Check if it contains the search string
        mask = column_as_str.str.contains(searchStr)

        # If the string is found in the column
        if mask.any():
            print(f Found "{searchStr}" in sheet "{sheet_name}" at: )

            # Get the row indices where the string is found
            row_indices = column_as_str[mask].index.values
            for row_idx in row_indices:
                print(f Row {row_idx + 1}, Column "{column_name}" )

        else:
            print(f "{searchStr}" not found in sheet "{sheet_name}", column "{column_name}" )

• 在排雷中心进行指挥:

C:Windowssystem32>python C:Users...path..program_name.py --search "THE STRING YOUR SEARCHING FOR GOES HERE" --file "C:Users..PATH..YOUR FILE.xlsb"





相关问题
import of excel in SQL imports NULL lines

I have a stored procedure that imports differently formatted workbooks into a database table, does work on them then drops the table. Here is the populating query. SELECT IDENTITY(INT,1,1) AS ID ...

Connecting to Oracle 10g with ODBC from Excel VBA

The following code works. the connection opens fine but recordset.recordCount always returns -1 when there is data in the table. ANd If I try to call any methods/properties on recordset it crashes ...

Excel date to Unix timestamp

Does anyone know how to convert an Excel date to a correct Unix timestamp?

C# GemBox Excel Import Error

I am trying to import an excel file into a data table using GemBox and I keep getting this error: Invalid data value when extracting to DataTable at SourceRowIndex: 1, and SourceColumnIndex: 1. As ...

Importing from excel "applications" using SSIS

I am looking for any tips or resources on importing from excel into a SQL database, but specifically when the information is NOT in column and row format. I am currently doing some pre-development ...