Interaction.CreateObject(String, String) Método

Definição

Cria e retorna uma referência a um objeto COM.Creates and returns a reference to a COM object. CreateObject não pode ser usado para criar instâncias de classes no Visual Basic, a menos que essas classes sejam explicitamente expostas como componentes COM.CreateObject cannot be used to create instances of classes in Visual Basic unless those classes are explicitly exposed as COM components.

public static object CreateObject (string ProgId, string? ServerName = "");
public static object CreateObject (string ProgId, string ServerName = "");
static member CreateObject : string * string -> obj
Public Function CreateObject (ProgId As String, Optional ServerName As String = "") As Object

Parâmetros

ProgId
String

Obrigatórios.Required. String.String. A ID do programa do objeto a ser criado.The program ID of the object to create.

ServerName
String

Opcional.Optional. String.String. O nome do servidor de rede no qual o objeto será criado.The name of the network server where the object will be created. Se ServerName for uma cadeia de caracteres vazia (""), o computador local será usado.If ServerName is an empty string (""), the local computer is used.

Retornos

Object

Cria e retorna uma referência a um objeto COM.Creates and returns a reference to a COM object. CreateObject não pode ser usado para criar instâncias de classes no Visual Basic, a menos que essas classes sejam explicitamente expostas como componentes COM.CreateObject cannot be used to create instances of classes in Visual Basic unless those classes are explicitly exposed as COM components.

Exceções

Servidor não disponívelServer is unavailable

Não existe nenhum objeto do tipo especificadoNo object of the specified type exists

Exemplos

O exemplo a seguir usa a CreateObject função para criar uma planilha do Microsoft Excel e salva a planilha em um arquivo.The following example uses the CreateObject function to create a Microsoft Excel worksheet and saves the worksheet to a file. Para usar este exemplo, o Excel deve ser instalado no computador em que este programa é executado.To use this example, Excel must be installed on the computer where this program runs. Além disso, você deve adicionar uma referência à biblioteca de tipos na guia com da caixa de diálogo Adicionar referência no menu projeto .Also, you must add a reference to the type library from the COM tab of the Add Reference dialog box on the Project menu. O nome da biblioteca de tipos varia dependendo da versão do Excel instalada em seu computador.The name of the type library varies depending on the version of Excel installed on your computer. Por exemplo, a biblioteca de tipos para o Microsoft Excel 2002 é denominada biblioteca de objetos do Microsoft excel 10,0.For example, the type library for Microsoft Excel 2002 is named Microsoft Excel 10.0 Object Library.

Sub TestExcel()
    Dim xlApp As Microsoft.Office.Interop.Excel.Application
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet

    xlApp = CType(CreateObject("Excel.Application"), 
                Microsoft.Office.Interop.Excel.Application)
    xlBook = CType(xlApp.Workbooks.Add, 
                Microsoft.Office.Interop.Excel.Workbook)
    xlSheet = CType(xlBook.Worksheets(1), 
                Microsoft.Office.Interop.Excel.Worksheet)

    ' The following statement puts text in the second row of the sheet.
    xlSheet.Cells(2, 2) = "This is column B row 2"
    ' The following statement shows the sheet.
    xlSheet.Application.Visible = True
    ' The following statement saves the sheet to the C:\Test.xls directory.
    xlSheet.SaveAs("C:\Test.xls")
    ' Optionally, you can call xlApp.Quit to close the workbook.
End Sub

Comentários

Para criar uma instância de um componente COM, atribua o objeto retornado por CreateObject a uma variável de objeto:To create an instance of a COM component, assign the object returned by CreateObject to an object variable:

Sub CreateADODB()  
   Dim adoApp As Object  
   adoApp = CreateObject("ADODB.Connection")  
End Sub  

O tipo de variável de objeto que você usa para armazenar o objeto retornado pode afetar o desempenho do aplicativo.The type of object variable you use to store the returned object can affect your application's performance. A declaração de uma variável de objeto com a As Object cláusula cria uma variável que pode conter uma referência a qualquer tipo de objeto.Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. No entanto, o acesso ao objeto por meio dessa variável é de associação tardia, ou seja, a associação ocorre quando o programa é executado.However, access to the object through that variable is late-bound, that is, the binding occurs when your program runs. Há muitos motivos pelos quais você deve evitar a ligação tardia, incluindo um desempenho de aplicativo mais lento.There are many reasons you should avoid late binding, including slower application performance.

Você pode criar uma variável de objeto que resulta na associação inicial, ou seja, a associação quando o programa é compilado.You can create an object variable that results in early binding - that is, binding when the program is compiled. Para fazer isso, adicione uma referência à biblioteca de tipos para seu objeto na guia com da caixa de diálogo Adicionar referência no menu projeto .To do so, add a reference to the type library for your object from the COM tab of the Add Reference dialog box on the Project menu. Em seguida, declare a variável de objeto do tipo específico de seu objeto.Then declare the object variable of the specific type of your object. Na maioria dos casos, é mais eficiente usar a Dim instrução e um assembly de interoperabilidade primário para criar objetos do que usar a CreateObject função.In most cases, it is more efficient to use the Dim statement and a primary interop assembly to create objects than it is to use the CreateObject function.

Interagindo com código não gerenciadoInteracting with Unmanaged Code

Outro problema é que objetos COM usam código de código não-gerenciado sem o benefício do Common Language Runtime.Another issue is that COM objects use unmanaged code - code without the benefit of the common language runtime. Há um grau razoável de complexidade envolvida na combinação do código gerenciado de Visual Basic com código não gerenciado do COM.There is a fair degree of complexity involved in mixing the managed code of Visual Basic with unmanaged code from COM. Quando você adiciona uma referência a um objeto COM, o Visual Basic procura um módulo de interoperabilidade primário (PIA) para essa biblioteca; se encontrar um, ele o usará.When you add a reference to a COM object, Visual Basic searches for a primary interop assembly (PIA) for that library; if it finds one, then it uses it. Se não encontrar um PIA, ele criará um assembly de interoperabilidade que contém classes de interoperabilidade locais para cada classe na biblioteca COM.If it does not find a PIA, then it creates an interoperability assembly that contains local interoperability classes for each class in the COM library. Para obter mais informações, consulte interoperabilidade com em aplicativos .NET Framework.For more information, see COM Interoperability in .NET Framework Applications.

Geralmente, você deve usar objetos fortemente vinculados e assemblies de interoperabilidade primária sempre que possível.You should generally use strongly bound objects and primary interop assemblies whenever possible. Os exemplos a seguir usam a CreateObject função com Microsoft Office objetos apenas para fins de demonstração.The examples below use the CreateObject function with Microsoft Office objects for demonstration purposes only. No entanto, esses objetos são mais fáceis de usar e mais confiáveis quando usados com o assembly de interoperabilidade primário apropriado.However, these objects are easier to use and more reliable when used with the appropriate primary interop assembly.

Criando um objeto em um computador remotoCreating an Object on a Remote Computer

Você pode criar um objeto em um computador remoto em rede passando o nome do computador para o ServerName argumento da CreateObject função.You can create an object on a remote networked computer by passing the name of the computer to the ServerName argument of the CreateObject function. Esse nome é o mesmo que a parte do nome do computador de um nome de compartilhamento: para um compartilhamento chamado " \ \MyServer\Public", ServerName é "meuservidor".That name is the same as the Machine Name portion of a share name: for a share named "\\MyServer\Public," ServerName is "MyServer."

Observação

Consulte a documentação COM (consulte Microsoft Developer Network) para obter informações adicionais sobre como tornar um aplicativo acessível em um computador remoto em rede.Refer to COM documentation (see Microsoft Developer Network) for additional information on making an application accessible on a remote networked computer. Talvez seja necessário adicionar uma chave do registro para seu aplicativo.You may need to add a registry key for your application.

O código a seguir retorna o número de versão de uma instância do Excel em execução em um computador remoto chamado MyServer :The following code returns the version number of an instance of Excel running on a remote computer named MyServer:

Sub CreateRemoteExcelObj()  
    Dim xlApp As Object  
    ' Replace string "\\MyServer" with name of the remote computer.  
    xlApp = CreateObject("Excel.Application", "\\MyServer")  
    MsgBox(xlApp.Version)  
End Sub  

Se o nome do servidor remoto estiver incorreto ou se não estiver disponível, ocorrerá um erro em tempo de execução.If the remote server name is incorrect, or if it is unavailable, a run-time error occurs.

Observação

Use CreateObject quando não houver nenhuma instância atual do objeto.Use CreateObject when there is no current instance of the object. Se uma instância do objeto já estiver em execução, uma nova instância será iniciada e um objeto do tipo especificado será criado.If an instance of the object is already running, a new instance is started, and an object of the specified type is created. Para usar a instância atual ou para iniciar o aplicativo e fazer com que ele carregue um arquivo, use a GetObject função.To use the current instance, or to start the application and have it load a file, use the GetObject function. Se um objeto tiver se registrado como um objeto de instância única, apenas uma instância do objeto será criada, independentemente de quantas vezes CreateObject for executada.If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Criando objetos de estruturaCreating Framework Objects

Você pode usar a CreateObject função somente para criar um objeto com.You can use the CreateObject function only to create a COM object. Embora não haja um mecanismo equivalente exato para criar um objeto .NET Framework, o Activator no System namespace contém métodos para criar objetos locais ou remotos.While there is no exact equivalent mechanism for creating a .NET Framework object, the Activator in the System namespace contains methods to create local or remote objects. Em particular, o CreateInstance método ou o CreateInstanceFrom método pode ser útil.In particular, the CreateInstance method or the CreateInstanceFrom method might be useful.

Importante

A CreateObject função requer permissão de código não-gerenciado, o que pode afetar sua execução em situações de confiança parcial.The CreateObject function requires unmanaged code permission, which might affect its execution in partial-trust situations. Para obter mais informações, consulte SecurityPermission e permissões de acesso ao código.For more information, see SecurityPermission and Code Access Permissions.

Aplica-se a

Confira também